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 an
expression of type 'const char *' discards qualifiers
[-Wincompatible-pointer-types]
char *ptr1 = source;
^ ~~~~~~
1 warning generated.
The code is very simple
#include<stdio.h>
char *my_strcpy(char *destination, const char *source);
int main(void) {
char str1[] = "this is something";
char str2[] = "123456789123456789";
my_strcpy(str2, str1);
puts(str2);
return 0;
}
char *my_strcpy(char *destination, const char *source) {
char *ptr1 = source;
char *ptr2 = destination;
while(*ptr1 != '\0') {
*ptr2++ = *ptr1++;
}
*ptr2 = '\0';
return destination;
}
any idea?
sourceis aconst 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 simplechar *suggests that the characters pointed to by theptr1pointer are not constant and you can now freely writeptr1[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 callbut in the code for some reason you write
you won’t get a compiler diagnostic message because
ptr1is 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).