C 指针 + 空闲 : Abort signal from abort(3) (SIGABRT)

标签 c

<分区>

我用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,它不是内存管理函数返回的指针,因此您具有所看到的行为。

关于C 指针 + 空闲 : Abort signal from abort(3) (SIGABRT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54824140/

相关文章:

c - 动态多维数组

编译共享库链接到其他.so

c - 如何在运行时在 C 中重新定义打印函数

c - 从文件中使用 malloc 和 realloc 读取

php - similar_text 是如何工作的?

c# - 通过套接字发送图像并将其保存在服务器上

C AVR 序列号 : Strange behaviour while using integers of different sizes

c - 将指针分配给指向 char 的指针数组

c - 在 C 编程中,如何用左侧的 0 填充我的二进制文件?

c - 管道、dup2 和 exec()