ProgrammingHardProduct company OA

What is wrong with this code?

What is wrong with this code?
char *p = malloc(10);
p++;
free(p);
  1. A. free must be given exactly the pointer malloc returned; passing p + 1 is undefined behaviour
  2. B. free needs the size of the block as a second argument
  3. C. It only leaks one byte
  4. D. Nothing: free releases the whole block containing p

Correct answer: A. free must be given exactly the pointer malloc returned; passing p + 1 is undefined behaviour

The allocator finds a block's bookkeeping from the exact address it handed out; any other pointer, even one inside the block, makes free undefined (often a crash or heap corruption). Keep the original pointer, or move a separate pointer.

More C Programming questions

Exams that ask this topic