gpt4 book ai didi

c++ - 难以理解 free() 的行为

转载 作者:太空狗 更新时间:2023-10-29 19:39:35 24 4
gpt4 key购买 nike

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;
}

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

最佳答案

这段代码在很多层面上都是非常错误的。

  1. Don't cast the return value来自 C 中的 malloc()
  2. 您分配的尺寸有误; ptr1 需要 sizeof *ptr1,而不是 sizeof (int)。这是一个指针!
  3. 记住 malloc() 可能会失败。使用前检查返回值。
  4. free()之后不要(只是不要)访问内存。未定义的行为。

另外,请注意当您在其上调用 free() 时,指针本身 并没有被销毁;消失的是指针指向的内存。因此,如果愿意,您仍然可以在指针本身中存储指针的位值。但是很少有需要这样做的情况,并且在/如果您检查这些位时应该小心。

关于c++ - 难以理解 free() 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12296663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com