无法在 C 中释放 const 指针 [英] Unable to free const pointers in C
本文介绍了无法在 C 中释放 const 指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何释放 const char*
?我使用 malloc
分配了新内存,当我试图释放它时,我总是收到错误不兼容的指针类型"
How can I free a const char*
? I allocated new memory using malloc
, and when I'm trying to free it I always receive the error "incompatible pointer type"
导致这种情况的代码类似于:
The code that causes this is something like:
char* name="Arnold";
const char* str=(const char*)malloc(strlen(name)+1);
free(str); // error here
推荐答案
有几个人发布了正确的答案,但出于某种原因,他们一直在删除它.您需要将其转换为非常量指针;free
采用 void*
,而不是 const void*
:
Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer; free
takes a void*
, not a const void*
:
free((char*)str);
这篇关于无法在 C 中释放 const 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文