gpt4 book ai didi

c - 自由 char*,当在 C 中作为 void 传递时

转载 作者:太空宇宙 更新时间:2023-11-04 05:37:37 25 4
gpt4 key购买 nike

我有这个功能

void clean_strs(void *p){
if (!p){
printf("Clean str ptr that is NULL !!\n");
fflush(stdout);
return;
}
char *a = (char*)p;
free(a);
a = NULL;
}

然后像这样传入一个指针:

char *a = malloc(4*sizeof(char));
// check if memory was allocated
if(a) {
a = "asd\0";
clean_strs(a);
a = NULL;
if(a) {
getchar();
}
}

产生信号 SIGABORT。有人可以解释为什么强制转换和释放动态分配的指针是错误的吗?

最佳答案

您没有释放动态分配的指针。你释放了一个指向常量的指针:

a = "asd\0";

您刚刚用指向字符串常量的指针替换了从 malloc 获得的值。除了从 malloc 获得的指针外,您不能释放任何指针。

你可能想要:

strcpy (a, "asd");

关于c - 自由 char*,当在 C 中作为 void 传递时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933377/

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