ProgrammingModerateProduct company OA

Why is the line `p = realloc(p, 2 * n * sizeof *p);` considered unsafe?

  1. A. realloc never moves the block, so the extra space may overwrite other data
  2. B. If realloc fails it returns NULL into p, so the still-allocated old block can no longer be reached or freed
  3. C. sizeof *p is evaluated after realloc returns, so the size is undefined
  4. D. realloc always frees the old block, so p dangles afterwards

Correct answer: B. If realloc fails it returns NULL into p, so the still-allocated old block can no longer be reached or freed

On failure realloc returns NULL but keeps the old block alive; overwriting p with NULL leaks it and loses the data. The fix is tmp = realloc(p, …); if (tmp) p = tmp;. sizeof does not evaluate its operand, and realloc may move the block when it must.

More C Programming questions

Exams that ask this topic