Cody Cody - 1 year ago 73
C Question

C - function returning a pointer to a local variable

Consider the following code.

int *abc(); // this function returns a pointer of type int

int main()
int *ptr;
ptr = abc();
printf("%d", *ptr);
return 0;

int *abc()
int i = 45500, *p;
p = &i;
return p;



I know according to link this type of behavior is undefined. But why i am getting correct value everytime i run the program.

Answer Source

Every time you call abc it "marks" a region at the top of the stack as the place where it will write all of its local variables. It does that by moving the pointer that indicates where the top of stack is. That region is called the stack frame. When the function returns, it indicates that it does not want to use that region anymore by moving the stack pointer to where it was originally. As a result, if you call other functions afterwards, they will reuse that region of the stack for their own purposes. But in your case, you haven't called any other functions yet. So that region of the stack is left in the same state.

All the above explain the behavior of your code. It is not necessary that all C compilers implement functions that way and therefore you should not rely on that behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download