Dangling Pointer in C

后端 未结 7 595
别跟我提以往
别跟我提以往 2020-12-07 05:02

I wrote a program in C having dangling pointer.

#include

int *func(void)
{
    int num;
    num = 100;
    return #
}

int func1(void         


        
相关标签:
7条回答
  • 2020-12-07 05:40

    Please study functions from basic C. Your concept is flawed...main should be

    int main(void)  
    {  
        int *a = func();  
        int b;
    
        b = func1();  
        printf("%d\n%d",*a,func1());  
        return 0;  
    }
    

    This will output 100 200

    0 讨论(0)
  • 2020-12-07 05:46

    It's undefined behavior. It could work correctly on your computer right now, 20 minutes from now, might crash in an hour, etc. Once another object takes the same place on the stack as num, you will be doomed!

    0 讨论(0)
  • 2020-12-07 05:46

    With dangling pointers, the result of a program is undefined. It depends on how the stack and the registers are used. With different compilers, different compiler versions and different optimization settings, you'll get a different behavior.

    0 讨论(0)
  • 2020-12-07 05:52

    Dangling pointers (pointers to locations that have been disassociated) induce undefined behavior, i.e. anything can happen.

    In particular, the memory locations get reused by chance* in func1. The result depends on the stack layout, compiler optimization, architecture, calling conventions and stack security mechanisms.

    0 讨论(0)
  • 2020-12-07 05:52

    Returning a pointer to a local variable yields undefined behaviour, which means that anything the program does (anything at all) is valid. If you are getting the expected result, that's just dumb luck.

    0 讨论(0)
  • 2020-12-07 05:55

    It's because of the way the memory gets allocated.

    After calling func and returning a dangling pointer, the part of the stack where num was stored still has the value 100 (which is what you are seeing afterwards). We can reach that conclusion based on the observed behavior.

    After the change, it looks like what happens is that the func1 call overwrites the memory location that a points to with the result of the addition inside func1 (the stack space previously used for func is reused now by func1), so that's why you see 200.

    Of course, all of this is undefined behavior so while this might be a good philosophical question, answering it doesn't really buy you anything.

    0 讨论(0)
提交回复
热议问题