C - function returning a pointer to a local variab

2019-01-20 10:46发布

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.

2条回答
Summer. ? 凉城
2楼-- · 2019-01-20 11:09

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.

查看更多
成全新的幸福
3楼-- · 2019-01-20 11:24

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.

查看更多
登录 后发表回答