Bat*_*nov 0 c pointers casting char
我有这个功能
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;
}
Run Code Online (Sandbox Code Playgroud)
并传入这样的指针:
char *a = malloc(4*sizeof(char));
// check if memory was allocated
if(a) {
a = "asd\0";
clean_strs(a);
a = NULL;
if(a) {
getchar();
}
}
Run Code Online (Sandbox Code Playgroud)
结果信号SIGABORT.有人可以解释为什么铸造和释放动态分配的指针是一个错误?
您没有释放动态分配的指针.你释放了一个指向常量的指针:
a = "asd\0";
Run Code Online (Sandbox Code Playgroud)
您刚刚malloc使用指向字符串常量的指针替换了您获得的值.free除了你得到的指针之外,你不能有任何指针malloc.
你可能想要:
strcpy (a, "asd");
Run Code Online (Sandbox Code Playgroud)