Discussion
What is the output of this C code?
#include <stdio.h>
int *f();
int main()
{
int *p = f();
printf("%d\n", *p);
}
int *f()
{
int *j = (int*)malloc(sizeof(int));
*j = 10;
return j;
}
Answer: A
Correct answer: 10
The storage is obtained from malloc, so it lives on the heap and its lifetime is independent of the function that allocated it. Returning the pointer is therefore legitimate, and the caller reads 10.
The contrast with returning the address of a local is the whole point: an automatic variable's lifetime ends when the function returns, leaving a dangling pointer. The only fault here is the missing free, which leaks the block - a leak rather than an error in the value printed.
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