Question says it all but here is an example:
typedef struct mutable_t{
int count, max;
void **data;
} mutable_t;
void pushMutable(mutable_t *m, void *object)
{
if(m->count == m->max){
m->max *= 2;
m->data = realloc(m->data, m->max * sizeof(void*));
}
// how to handle oom??
m->data[m->count++] = object;
}
How can I handle running out of memory and not NULL out all of my data?
edit - let's assume there is something which could be done e.g. free up some memory somewhere or at least tell the user "you can't do that - you're out of memory". Ideally I would like to leave what was allocated there.
realloc()
(in your case) would be to dom->max /= 4; m->max *= 3;
and try callingrealloc()
again to see if we can still squeeze a few more bytes out. You could even try a couple times with successively smaller sizes, but at some point it won't be worth it. – Pearlstein