Unable to free const pointers in C

前端 未结 12 1789
梦如初夏
梦如初夏 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条回答
  •  眼角桃花
    2020-11-28 07:28

    I think the real answer is that free should take a const pointer argument and NULL should be defined as a const pointer. This seems to be a bug in the standards. Freeing a const pointer should be implemented as follows:

    free(p);
    p = NULL;
    

    I don't see how a compiler could generate incorrect code in this case, the const pointer p is no longer accessible, so it doesn't matter if the object it pointed to is const, valid, whatever else. Its const so there can't be any dirty copies in registers or anywhere else. It is valid to set a const pointer to another value, and the fact that that value is NULL doesn't matter because the previous value is no longer accessible.

提交回复
热议问题