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
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).