ProgrammingVery hard

Which realloc pattern does not leak memory or lose the original block if the reallocation fails?

  1. A. p = realloc(p, newsize); if (!p) exit(1);
  2. B. int *t = realloc(p, newsize); if (!t) { /* p still valid */ } else p = t;
  3. C. free(p); p = malloc(newsize);
  4. D. p = realloc(p, newsize); if (p == NULL) free(p);

Correct answer: B. int *t = realloc(p, newsize); if (!t) { /* p still valid */ } else p = t;

realloc returns NULL on failure and leaves the old block valid, so assigning the result straight back to p loses the pointer. The temporary keeps the old block reachable.

More C Programming questions

Exams that ask this topic