The trick to fixing the "nulled but not freed after failure" error is to save the value returned by realloc into a separate pointer and check it for NULL before reassigning the old pointer:
char **tmp = (char **) realloc(result, sizeof(char *) * (n + 1)); if (tmp) { result = tmp; } else { ...
Now that the result assignment is protected with a NULL check, you have the old value to work with: you could free it if you want, or you can continue to use it if you need to. On the other hand, the source code does not give you the same opportunity.
Note. . When you pass a NULL pointer to realloc , it behaves like a malloc . This is why you can refuse a conditional expression when using realloc for the first time - replace this
if (result == (char **) 0) result = (char **) malloc(sizeof(char *)); else result = (char **) realloc(result, sizeof(char *) * (n + 1));
with this:
char** tmep = (char **) realloc(result, sizeof(char *) * (n + 1)); ...
Remember to set n to zero - it is currently used uninitialized, which corresponds to undefined.
source share