realloc() can easily return NULL when downsizing.
void *ptr = malloc(10); ptr = realloc(ptr, 0); if (ptr == NULL) { puts("Failure because return value is NULL? - not really"); }
realloc(any_pointer, 0) may return NULL or maybe some not-NULL pointer, this implementation is defined.
This is why realloc()/malloc() failure should not be a simple if (ptr == NULL) test, but
void *ptr = malloc(newsize); // or realloc(..., newsize) if (ptr == NULL && newsize > 0) { exit(0); // Handle OOM; }
Because of this ambiguity, the code should make the realloc() wrapper, recommend something like:
void *xrealloc(void *ptr, size_t newsize, bool *falure) { *failure = 0; if (newsize > 0) { void *tmp = realloc(ptr, newsize); if (tmp == NULL) { *failure = 1; return ptr;
Getting NULL in realloc() with a reduced size, therefore, is not a failure, and therefore this answer only tangentially, but the OP question: "... force realloc if the new block size is less than the initial?" and then used the less reliable if (ptr == NULL) paradigm.
chux
source share