Unable to free const pointers in C

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

    It makes no sense to malloc a pointer to const, since you will not be able to modify its contents (without ugly hacks).

    FWIW though, gcc just gives a warning for the following:

    //
    // const.c
    //
    
    #include 
    #include 
    
    int main(void)
    {
        const char *p = malloc(100);
    
        free(p);
        return 0;
    }
    
    $ gcc -Wall const.c -o const
    const.c: In function ‘main’:
    const.c:8: warning: passing argument 1 of ‘free’ discards qualifiers from pointer target type
    $ 
    

    What compiler are you using ?

提交回复
热议问题