[英]Does freeing an uninitialized pointer result in undefined behavior?
If you have a pointer that is not initialized and, by mistake, try to free it, is this going to result in undefined behavior? 如果你有一个未初始化的指针,并且错误地尝试释放它,这是否会导致未定义的行为?
Like: 喜欢:
int main(void){
char *string;
free(string);
return 0;
}
Does freeing an uninitialized pointer result in undefined behavior?
释放未初始化的指针会导致未定义的行为吗?
Yes. 是。
However, freeing a null pointer is well-defined. 但是,释放空指针是明确定义的。
From the C99 standard: 从C99标准:
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation.free
函数导致ptr
指向的空间被释放,即可用于进一步分配。 Ifptr
is a null pointer, no action occurs.如果
ptr
是空指针,则不执行任何操作。 Otherwise, if the argument does not match a pointer earlier returned by thecalloc
,malloc
, orrealloc
function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined .否则,如果参数与
calloc
,malloc
或realloc
函数先前返回的指针不匹配,或者如果通过调用free
或realloc
释放了空间,则该行为是undefined 。
Yes, because accessing any uninitialised variable provokes undefined behaviour. 是的,因为访问任何未初始化的变量会引发未定义的行为。
This includes passing an uninitialise pointer to free()
. 这包括将一个uninitialise指针传递给
free()
。 This itself also includes the case where the uninitialise pointer "by accident" may have a value equal to NULL
. 这本身还包括“意外”未初始化指针的值可能等于
NULL
。
Yes, it is undefined behavior. 是的,这是未定义的行为。
The pointer passed to free
should be a pointer to a valid object allocated with malloc
, calloc
, realloc
or a null pointer. 传递给
free
的指针应该是指向使用malloc
, calloc
, realloc
或空指针分配的有效对象的指针。
From C99: 从C99:
(7.20.3.2p2) "If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."
(7.20.3.2p2)“如果ptr是空指针,则不执行任何操作。否则,如果参数与calloc,malloc或realloc函数先前返回的指针不匹配,或者如果空间已被调用解除分配为了释放或重新分配,行为是不确定的。“
是的,确实如此,因为您应该只free()
1.为NULL
或2.是通过调用malloc()
, calloc()
或realloc()
获得的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.