Discussion
What is the output of this C code?
#include <stdio.h>
int main()
{
int i = 97, *p = &i;
foo(&p);
printf("%d ", *p);
return 0;
}
void foo(int **p)
{
int j = 2;
*p = &j;
printf("%d ", **p);
}
Answer: A
Correct answer: Undefined behaviour
foo is given the address of the caller's pointer, so *p = &j does change main's p - that part works, and foo prints 2.
But j is an automatic variable of foo, and its lifetime ends when foo returns. main is then left with a dangling pointer, and *p is undefined behaviour. In practice the stack often still holds 2, which is why the value usually appears - but the compiler is entitled to assume the case never arises.
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