【发布时间】:2020-05-12 16:34:56
【问题描述】:
我在运行此代码时收到以下错误。
`main' 中的错误:free():无效指针:
我的想法是使用通过 malloc 分配的指针。这是一个示例代码。 请告诉我为什么会收到此错误。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int c=10;
int* ptr = NULL;
ptr = (int*)malloc(sizeof(int));
if(ptr == NULL)
{
printf("Memory not allocated");
exit(0);
}
ptr = &c;
free(ptr);
ptr=NULL;
}
【问题讨论】:
-
ptr = &c;是干什么用的? -
ptr = malloc(...)后跟ptr = &c类似于例如int a; a = 10; a = 20;然后想知道为什么a不再等于10。也许你应该这样做*ptr = c? -
并注意使用
=的赋值和使用==进行相等比较之间的区别。您实际上分配给ptr三次次。 -
感谢您指出 == 运算符。 *ptr = c 以分段错误结束。我遇到了另一个问题,我将所有不必要的代码都删除到这里。