gpt4 book ai didi

c - 为什么 free() 不释放所有分配的内存位置?

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:18 25 4
gpt4 key购买 nike

<分区>

不知道是我哪里做错了还是我的观念有些不对

#include<stdio.h>
#include<stdlib.h>

int main()
{
int *p;
p=calloc(3,sizeof(int));
p[0]=10;
p[1]=15;
p[2]=30;
printf("\n%d\n%p\n%d\n%p\n%d\n%p\n\n",p[0],p,p[1],p+1,p[2],p+2);
free(p);
//p=NULL;
printf("\n%d\n%p\n%d\n%p\n%d\n%p\n\n",p[0],p,p[1],p+1,p[2],p+2);
return 0;
}

当第二次运行 printf() 时,它显示 p[2]=30,而 p[0]=p[1]=0(在 gcc ubuntu 中和 Code::Blocks windows 中的一些任意值)。我有 2 个问题。

  1. 为什么 free() 释放前 2 个指针而不是第 3 个。一个?
  2. 当显示任意值似乎是正确的时候,为什么在 ubuntu 中显示的值是 0?

我是初学者,所以请多多包涵。我用 malloc() 尝试过同样的事情,同样的事情发生了。

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