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, voi
The standard technique is to introduce a new variable to hold the return from realloc. You then only overwrite your input variable if it succeeds:
tmp = realloc(orig, newsize);
if (tmp == NULL)
{
// could not realloc, but orig still valid
}
else
{
orig = tmp;
}
There's also another subtle error that can come from realloc. The memory leak coming from returned NULL pointer is rather well known (but quite rare to stumble upon). I had in my program a crash once in a while that came from a realloc call. I had a dynamic structure that adjusted its size automatically with a realloc resembling this one:
m->data = realloc(m->data, m->max * sizeof(void*));
The error I made was to not check for m->max == 0, which freed the memory area. And made from my m->data pointer a stale one.
I know it's a bit off-topic but this was the only real issue I ever had with realloc.