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;
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development