p points to the third element of a block obtained from malloc. What happens if the program calls free(p)?
Correct answer
A. Undefined behaviour, because free needs the pointer that malloc returned
17 views
A. Undefined behaviour, because free needs the pointer that malloc returned
17 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is A? Ask here and get an explanation.