A buffer is grown with p = realloc(p, 2 * n); and the call fails. What is the correct statement?
Correct answer
D. The original block is untouched and still allocated, so assigning the result directly to p leaks it
16 views
D. The original block is untouched and still allocated, so assigning the result directly to p leaks it
16 views
realloc returns NULL on failure and leaves the original allocation valid, which is why the result must go into a temporary pointer before replacing p. Direct assignment destroys the only reference to the old block, a leak that LeakSanitizer will flag. The usual fix is void *tmp = realloc(p, 2*n); if (tmp) p = tmp; else handle_error().
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.