ProgrammingHardProduct company OA · GATE CS

After `int *q = realloc(p, 2 * n * sizeof *q);` succeeds (q is not NULL), where p pointed to n ints, which statement is true?

  1. A. The n new ints at the end are zero-initialised
  2. B. p and q always hold the same address
  3. C. p must still be freed separately from q
  4. D. The first n ints are preserved in q, and p must not be used any more because the block may have moved

Correct answer: D. The first n ints are preserved in q, and p must not be used any more because the block may have moved

realloc keeps the old contents up to the smaller size, but it may move the block, after which the old pointer is invalid; only q may be used and freed. The added part is uninitialised (unlike calloc), and freeing p as well would be a double free.

More C Programming questions

Exams that ask this topic