free() 具有不同指针的相同堆内存
free() same Heap memory with diffrent Pointers
int main()
{
int* Pointer;
Pointer = (int*)malloc(sizeof(int));
*Pointer = 33;
int * Pointer2 = Pointer;
printf("%d\n", *Pointer);
free(Pointer);
free(Pointer2);
return 0;
}
输出是:
33
没有错误或警告。
我对指向同一个堆地址的两个指针进行了 declered。
我知道释放它们两个很麻烦,这里只需要使用一个免费的(一个 malloc 一个免费的)但是如果我这样做(释放它们两个),它会是未定义的吗?或者可以这样做它只是不会做任何事情来从不同的指针(Pointer 和 Pointer2)释放相同的堆区域?
根据 C11 standard draft 7.22.3.3p2
The free
function causes the space pointed to by ptr
to be
deallocated, that is, made available for further allocation. If ptr is
a null
pointer, no action occurs. Otherwise, if the argument does not
match a pointer earlier returned by a memory management function, or
if the space has been deallocated by a call to free
or realloc
,
the behavior is undefined.
(重点是我的..)
int main()
{
int* Pointer;
Pointer = (int*)malloc(sizeof(int));
*Pointer = 33;
int * Pointer2 = Pointer;
printf("%d\n", *Pointer);
free(Pointer);
free(Pointer2);
return 0;
}
输出是: 33 没有错误或警告。 我对指向同一个堆地址的两个指针进行了 declered。 我知道释放它们两个很麻烦,这里只需要使用一个免费的(一个 malloc 一个免费的)但是如果我这样做(释放它们两个),它会是未定义的吗?或者可以这样做它只是不会做任何事情来从不同的指针(Pointer 和 Pointer2)释放相同的堆区域?
根据 C11 standard draft 7.22.3.3p2
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. If ptr is anull
pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.
(重点是我的..)