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
在很多层面上,这段代码非常错误.
malloc()C中转换返回值.ptr1需要sizeof *ptr1,而不是sizeof (int).这是一个指针!malloc()可能会失败.使用前请检查返回值.free().未定义的行为.另请注意,当您调用指针时,指针本身不会被销毁free(); 消失的东西是指针所指的内存.因此,如果您愿意,您仍然可以在指针本身中存储指针的位数.尽管如此,在很少的情况下需要这样做,并且在检查这些位时应该小心.