Unable to free const pointers in C

前端 未结 12 1793
梦如初夏
梦如初夏 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

    You cannot free const char * because it is const. Store pointers received from malloc in non-const pointer variables, so that you can pass them to free. You can pass char * arguments to functions taking const char * arguments but opposite is not always true.

    void foo (const char *x);
    char *ptr = malloc (...);
    foo (ptr);
    free (ptr);
    

提交回复
热议问题