Will C reuse the memory of a local block var once it goes out of scope?

后端 未结 4 796
执笔经年
执笔经年 2021-01-21 21:01

(I believe this question is technically distinct from Can a local variable's memory be accessed outside its scope? because it is C instead of C++.)

I know that in C

相关标签:
4条回答
  • 2021-01-21 21:26

    The C99, 6.2.4 p2 standard says:

    If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.

    0 讨论(0)
  • 2021-01-21 21:27

    It's undefined behavior. It may work on some architectures or operating systems, but don't count on it. An example of where it may work is Linux, with the red zone enabled.

    0 讨论(0)
  • 2021-01-21 21:34

    Is it nonetheless still SAFE to use that memory until the end of the function?

    No, it is not. Once the variable is out of scope, any reference to the memory that it once occupied is undefined behavior.

    Here is a short demo with UB happening when the compiler reuses memory allocated inside a block:

    int *ptr1, *ptr2;
    {
        int x[8];
        scanf("%d", x);
        printf("You entered x=%d\n", x[0]);
        ptr1 = x;
    }
    {
        int y[8];
        scanf("%d", y);
        printf("You entered y=%d\n", y[0]);
        ptr2 = y;
    }
    printf("Now x=%d\n", *ptr1); // <<== Undefined behavior!!!
    printf("Now y=%d\n", *ptr2); // <<== Undefined behavior!!!
    

    I made an array because the compiler used for the demo chooses to not reuse memory of individual variables and smaller arrays. Once a certain threshold is crossed, however, the memory is reused.

    Demo.

    This demo shows how the address of int x[8] is reused for int y[8].

    0 讨论(0)
  • 2021-01-21 21:34

    You cannot safely look at what that pointer points to, once you're outside the block, exactly as you suspect.

    The "memory location" that was used for the value of X, of course, lives on, so something is likely to be there. But accessing it has no guaranteed safe result; you're likely to see garbage, and in extreme cases it might even crash the program. (And for some amount of time, you might find that the original value of X is still present! That's a red herring; it doesn't make it OK to use.)

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