我用C写了下面的代码:
#include <stdio.h>
#include <stdlib.h>
int main (int argc , char *argv[]) {
int * ptr = (int *)malloc(sizeof(int));
int three = 3;
ptr = &three;
free(ptr);
return EXIT_SUCCESS;
}
当我执行时出现以下错误:
Abort signal from abort(3) (SIGABRT).
你能帮我找出我的错误吗?
谢谢你!
您拥有的是未定义的行为。 C11 标准规定:
7.22.3.3 The free function
...
2 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.
在您的示例中,free
的参数是 &three
,它不是内存管理函数返回的指针,因此您具有所看到的行为。