Discussion
Output?
#include <stdio.h>
#include <stdlib.h>
void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}
int main()
{
int *p;
fun(p);
*p = 6;
printf("%d\n",*p);
return(0);
}
Answer: A
Correct answer: May not work
The pointer is passed by value, so fun receives a copy. Assigning the result of malloc to that copy changes nothing in main, where p is still uninitialised.
Writing *p = 6 then dereferences an indeterminate pointer, which is undefined behaviour - it may crash, may appear to work, may corrupt something else. To change the caller's pointer the function would need a int ** parameter, or it would have to return the new address.
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