A dangling pointer, the reason for the change in value after free ()?

In the next code segment, after free(x), why ybecomes 0?

According to my understanding, the memory in the heap that it pointed to x, and still pointed to y, was not assigned to someone else, as it could change to 0

And more than that, I don’t think it is free(x)that which changed it to 0.

Any comments?

#include <stdio.h>

int main(int argc, char *argv[])
{
    int *y = NULL;
    int *x = NULL;

    x = malloc(4);
    *x = 5;

    y = x;
    printf("[%d]\n", *y); //prints 5

    free(x);

    printf("[%d]\n", *y); //why doesn't print 5?, prints 0 instead

    return 0;
}
+2
source share
4 answers

This behavior is undefined, the explanation is just speculation.

I can assume that you are probably using the debug version of the C library and that the debug version of free () makes the scope zero.

+12

, free, . .

, undefined.

+4

y , x,

y = x;

x, , y.

, "0", undefined, , "0".

"Binky pointer fun video" ( , ), .

+2

free() , , malloc(), , C runtime ( -, " " ).

, y ( , , ).

- , , , , (, 't , , ).

, , , , , , . , , , (.. NULL "" ). , MSVC-debug 0xDD (. 0xCD, 0xDD .. malloc/free/new/delete? ).

+2

Source: https://habr.com/ru/post/1765673/


All Articles