Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - function returning a pointer to a local variable

Consider the following code.

#include<stdio.h>
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;
}

Output:

45500

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

like image 665
Cody Avatar asked Sep 07 '16 15:09

Cody


2 Answers

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.

like image 68
redneb Avatar answered Oct 20 '22 03:10

redneb


Well, undefined behavior is, undefined. You can never rely on UB (or on an output of a program invoking UB).

Maybe, just maybe in your environment and for your code, the memory location allocated for the local variable is not reclaimed by the OS and still accessible, but there's no guarantee that it will have the same behavior for any other platform.

like image 34
Sourav Ghosh Avatar answered Oct 20 '22 03:10

Sourav Ghosh