Unable to free const pointers in C

前端 未结 12 1809
梦如初夏
梦如初夏 2020-11-28 06:56

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 pointe

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 07:40

    Several answers have suggested simply casting to char*. But as el.pescado wrote above,

    casting const to non-const is a symptom of code smell.

    There are compiler warnings that guard against this, such as -Wcast-qual in gcc, which I find very useful. If you really have a valid case for freeing a const pointer (contrary to what many have written here, there are valid cases, as pointed out by nlstd), you could define a macro for that purpose like this:

    #define free_const(x) free((void*)(long)(x))
    

    This works at least for gcc. The double cast makes the logic -Wcast-qual not detect this as "casting const away". Needless to say, this macro should be used with care. Actually it should only be used for pointers allocated in the same function.

提交回复
热议问题