Discussion
What will be the output of the following 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: 2 2
foo now takes a int ** and is given &p, so it can reach the caller's pointer itself. Assigning *p = &j changes main's p to point at j, and both prints show 2.
There is a hazard concealed in the output, though: j is local to foo and its lifetime ends when foo returns, so main's p is left dangling. The second print happens to find 2 still in that stack location, but reading it is undefined behaviour.
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