Reputation: 9
#include<stdio.h>
int *fun();
main()
{
int *i;
i=fun();
printf("cbgg\n");
printf("%d",*i);
getch();
}
int *fun()
{
int k;
k=5;
return (&k);
}
Though the program written above prints a garbage value for i, yet the the program written below works fine,i.e. the output is absolutely relevant, which is 5. Why is this so?
#include<stdio.h>
int inc();
main()
{
int i;
i=inc();
printf(“cbgg\n”);
printf(“%d”,i);
getch();
}
int inc()
{
int k;
k=5;
return (k);
}
Upvotes: 0
Views: 81
Reputation: 36102
To understand this you need to know a little bit about how arguments are passed to and from functions. When "fun" is called the arguments to "fun" are pushed on the stack (among other things). For "fun" to return values it pushes them on the stack and the caller later pops the value.
The local variable int k has function scope so when the function "fun" exits the stack space used is destroyed. Returning a pointer to that destroyed memory area is undefined behavior and that is what you are doing when you return &k. In #2 you instead push the value of k on the stack and that is valid.
Upvotes: 1
Reputation: 3275
The main difference is that this one does a pretty nasty thing by returning the address of a local variable (allocated on the stack) - Later usage of the returned pointer calls for undefined behavior.
int *fun()
{
int k;
k=5;
return (&k);
}
The other one is just a harmless return of 5 from the fun()
routine.
Upvotes: 4
Reputation: 2547
In first case you are returning pointer to local variable,whose scope is limited to function only. Whenever you return from function stack gets modified and you get unexpected data.
Upvotes: 0