bhavneet
bhavneet

Reputation: 61

Pointers not giving expected result

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 usingprintf("%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

Answers (2)

John Bode
John Bode

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

Some programmer dude
Some programmer dude

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

Related Questions