Reputation: 1700
#include <stdio.h>
void modify(char **s){
char *new_name = "Australia";
*s = new_name;
}
int main(){
char *name = "New Holland";
modify(&name);
printf("%s\n", name);
return 0;
}
Here we are trying to modify string literal name
of char*
type which is stored in a read-only location. So does this fall into undefined behavior?
Upvotes: 0
Views: 68
Reputation: 67546
First of all, you do not modify the string; you assign to the pointers, and pointers are not strings! They can only reference the C strings (which are nul-terminated arrays of char
).
It's my understanding of the C standard (6.5.2.5 - especially examples, quoted below) that string literals have a static
storage duration, and it is not UB as you assign the reference to the string literal (not the local variable). It does not matter where string literals are physically stored.
EXAMPLE 5 The following three expressions have different meanings:
"/tmp/fileXXXXXX" (char []){"/tmp/fileXXXXXX"} (const char> []){"/tmp/fileXXXXXX"}
The first always has static storage duration and has type array of char, but need not be modifiable; the last two have automatic storage duration when they occur within the body of a function, and the first of these two is modifiable.
Upvotes: 3