难以理解free()的行为

Ras*_*yak 3 c c++ malloc free visual-studio-2010

int main()
{
    int *ptr, **ptr1;
    ptr = (int*)malloc(sizeof(int));
    ptr1 = (int**)malloc(sizeof(int));
    free(ptr);
    *ptr = 12345;
    ptr1 = &ptr;

    //free(ptr);
    //**ptr1 = 23456;
    printf("%d \n", **ptr1);
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当内存已经存在时,如何*ptr存储值?所以,现在 应该指向.为什么会这样?12345freedptrgarbage

unw*_*ind 8

在很多层面上,这段代码非常错误.

  1. 不要malloc()C中转换返回值.
  2. 你分配的是错误的尺码; ptr1需要sizeof *ptr1,而不是sizeof (int).这是一个指针!
  3. 请记住,malloc()可能会失败.使用前请检查返回值.
  4. 你没有(只是)访问内存free().未定义的行为.

另请注意,当您调用指针时,指针本身不会被销毁free(); 消失的东西是指针所指的内存.因此,如果您愿意,您仍然可以在指针本身中存储指针的位数.尽管如此,在很少的情况下需要这样做,并且在检查这些位时应该小心.

  • @ 1.平心而论,问题也标记为C++.但话说回来,你不会在C++中使用`malloc`. (3认同)