Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this program?

#include <stdio.h>
#include <stdlib.h>
int main()
{
   int *numbers = (int*)calloc(4, sizeof(int));
   numbers[0] = 2;
   free(numbers);
   printf("Stored integers are ");
   printf("numbers[%d] = %d ", 0, numbers[0]);
   return 0;
}

 

  • A.Garbage value
  • B.2
  • C.Compilation error

Answer: A

Correct answer: Garbage value

The block is freed and then read through the same pointer. Once free has been called the memory belongs to the allocator again and may be reused or unmapped, so numbers[0] reads whatever happens to be there.

This is use after free, and it is undefined behaviour rather than merely unlucky - the program may print 2, may print rubbish, or may crash. It is particularly insidious because the old value often survives long enough to make the code look correct in testing.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.