gpt4 book ai didi

C free()分配内存两次,会导致段错误吗?

转载 作者:行者123 更新时间:2023-11-30 20:56:40 27 4
gpt4 key购买 nike

如果我们两次free()使用malloc()分配的同一个char指针,会导致segfalut吗?

void Allocate() 
{
char *y;
y = (char *) malloc (sizeof(char) * 200);
free (y);
strcpy(y,"helloworld");
free (y);
}

int main()
{
Allocate();
return 0;
}

最佳答案

这是未定义的行为,所以不要这样做。

更重要的是,在调用free()之后不要使用内存,这是绝对禁止的:

free (y);
strcpy(y,"helloworld");

以上也是未定义的行为。

此外,don't cast the return value of malloc() in C .

关于C free()分配内存两次,会导致段错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22451228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com