为什么不免费()释放所有分配的内存位置? [英] Why does not free() deallocate all allocated memory locations?
问题描述
我不知道如果我做错了什么,如果我的观念是错误的有些
I don't know if I am doing something wrong or if my concept is somewhat wrong
#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(海合会Ubuntu和在code一些arbitary值:: Blocks的视窗)。我有2个问题。
When the 2nd, printf() is run, it shows p[2]=30, whereas p[0]=p[1]=0 (in gcc ubuntu and some arbitary values in Code::Blocks windows). I have 2 questions.
- 为什么免费()释放前2个三分球,而不是第三位。一个?
- 为什么在Ubuntu中显示0值时,它似乎是正确显示arbitary值?
我是初学者所以请大家多多包涵。我曾尝试使用malloc()一样的事情,同样的事情发生了。
I am a beginner so please bear with me. I have tried the same thing with malloc(), and same thing happens.
推荐答案
使用内存已是免费()
-d调用的未定义行为。 不要那样做。的
Using memory that has already been free()
-d invokes undefined behavior. Don't do that.
引用 C11
附件§J.2,未定义行为的
这是指通过调用释放空间指针的值免费
或
的realloc
使用功能。
The value of a pointer that refers to space deallocated by a call to the
free
orrealloc
function is used.
要详细说明,称免费()
上一个指针不将指针设置为 NULL
或其他任何东西。它只是标记存储器中作为可重复使用的由存储器管理器。该内存位置(指针)不是的有效的了的节目,所以你不应该用它来。
To elaborate, calling free()
on a pointer does not set the pointer to NULL
or anything else. It just marks the memory as re-usable by the memory manager. That memory location (pointer) is not valid anymore for the program, so you should not be using it.
作为preventive措施,上述的问题,它被认为一个良好的编码习惯调用后无明确设置指向
。然而,FWIW,这不是的强制的 NULL
()
As a preventive measure to the above problem, it's considered a good coding practice to set the pointer to NULL
explicitly after calling free()
. However, FWIW, this is not mandatory.
引用 C11
,章7.22.3.3
Quoting C11
, chapter 7.22.3.3
的免费
功能使空间指向 PTR
被释放,也就是说,国产
可用于进一步分配。 [...]
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. [...]
另外,我想补充,的部分免费()
的是不可能通过调用免费()
,无论如何。您可以参照本previous答案澄清。
Also, just to add, partial free()
is not possible by calling free()
, anyway. You can refer to this previous answer for clarification.
这篇关于为什么不免费()释放所有分配的内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!