Reputation: 61
I am a beginner. I was working around with pointer when I found something strange:
#include<stdio.h>
int* fun(int*);
int main()
{
int i=4,*j;
j=fun(&i);
printf("%d ",*j);//gives correct answer -> how??
printf("%d",*j);//gives incorrect answer
}
int* fun(int *i)
{
int k;
k=*i;
return (&k);
}
In main(), I am using
printf("%d ",*j);` 2 times. First one is giving me right answer, but second one is not. Why?
but this is working fine- #include int *func();
int main()
{
int *p;
p=func();
printf("%u", p);
printf("\n%d", *p);
printf("\n%d", *p);
printf("\n%d", *p);
printf("\n%d", *p);
}
int* func()
{
int i=10;
printf("%u", &i);
printf("\n%d", i);
return (&i);
}
Upvotes: 0
Views: 115
Reputation: 123578
You're returning the address of a variable that's local to fun
; once fun
exits, that variable no longer exists, and the pointer is no longer valid. Strictly speaking, the behavior is undefined.
What's most likely happening is that the memory location that k
used to occupy gets overwritten after the first call to printf
.
Upvotes: 2
Reputation: 409442
You are invoking undefined behavior by returning a pointer to a local variable. After the function fun
returns, the space occupied by the local variable k
is not valid anymore. Actually the space on the stack previously used by fun
is probably overwritten by the first call to printf
.
Upvotes: 8