自由 char*,当在 C 中作为 void 传递时
Free char*, when passed as a void in C
我有这个功能
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[=11=]";
clean_strs(a);
a = NULL;
if(a) {
getchar();
}
}
产生信号 SIGABORT。有人可以解释为什么动态分配的强制转换和释放指针是错误的吗?
您没有释放动态分配的指针。您释放了指向常量的指针:
a = "asd[=10=]";
您刚刚用指向字符串常量的指针替换了从 malloc
获得的值。你不能 free
除了你从 malloc
.
得到的任何指针
您可能想要:
strcpy (a, "asd");
我有这个功能
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[=11=]";
clean_strs(a);
a = NULL;
if(a) {
getchar();
}
}
产生信号 SIGABORT。有人可以解释为什么动态分配的强制转换和释放指针是错误的吗?
您没有释放动态分配的指针。您释放了指向常量的指针:
a = "asd[=10=]";
您刚刚用指向字符串常量的指针替换了从 malloc
获得的值。你不能 free
除了你从 malloc
.
您可能想要:
strcpy (a, "asd");