Why I get; initializing 'char *' with an expression of type 'const char *' discards qualifiers?

后端 未结 6 1169
陌清茗
陌清茗 2021-01-05 05:37

I can\'t figure out why I get this warning from clang by myself:

function_prototype_const_modifier.c:13:8: warning: initializing \'char *\' with         


        
6条回答
  •  [愿得一人]
    2021-01-05 06:21

    source is a const char *, a pointer to const characters, so the characters cannot be changed by dereferencing the pointer (i. e. source[0] = 'A'; is a constraint violation).

    However, assigning it to a char * discards this constraint; a simple char * suggests that the characters pointed to by the ptr1 pointer are not constant and you can now freely write ptr1[0] = 'A'; without getting compiler errors (a "diagnostic message").

    Consider what this means when you pass in a string literal. Since a string literal is "readonly" (it's a const char []), trying to modify its contents is undefined behavior. So if you call

    my_strcpy(destination, "Constant String");
    

    but in the code for some reason you write

    ptr1[0] = 'A';
    

    you won't get a compiler diagnostic message because ptr1 is a pointer to non-const chars, but your program will still invoke undefined behavior (and in practice, most likely crash, since string literals are placed in readonly memory regions).

提交回复
热议问题