1. Home
  2. Computer Science MCQs
  3. C Programming
  4. A buffer is grown with p = realloc(p, 2 * n); and the call…

Added 30 Nov -0001

A buffer is grown with p = realloc(p, 2 * n); and the call fails. What is the correct statement?

  1. The original block is automatically freed before the call returns, so p is left as a null pointer
  2. The original block is truncated to half its size before the failure, so the buffer keeps only its data
  3. realloc cannot fail when the new size is larger than the old one, because growth always happens in place
  4. The original block is untouched and still allocated, so assigning the result directly to p leaks it Correct answer

Correct answer

D. The original block is untouched and still allocated, so assigning the result directly to p leaks it

16 views

MCQSEXAM

Explanation

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().

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs