1. Home
  2. Computer Science MCQs
  3. C Programming
  4. p points to the third element of a block obtained from…

Added 30 Nov -0001

p points to the third element of a block obtained from malloc. What happens if the program calls free(p)?

  1. Undefined behaviour, because free needs the pointer that malloc returned Correct answer
  2. Only the memory beyond p is released, and the earlier part stays allocated
  3. The call is legal and releases the whole block through the allocation header
  4. A diagnostic is guaranteed, since free can detect an interior pointer

Correct answer

A. Undefined behaviour, because free needs the pointer that malloc returned

17 views

MCQSEXAM

Explanation

free requires the exact pointer value returned by malloc, calloc or realloc, because the allocator stores its bookkeeping immediately before that address. Passing an interior pointer is undefined behaviour, and the runtime is not obliged to detect it. Note that freeing a null pointer is well defined and does nothing, which is a different case from freeing an offset pointer.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? 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