I always though that char s[]
and char *s
were essentially the same in simple C functions.
Yet the following code gives me a segmentation fault
at runtime.
int main() {
char s1[] = "str 1";
s1[1] = 'T';
printf("%sn", s1); // <-- This line prints "sTr 1"
char* s2 = "str 2";
s2[1] = 'T'; // <-- This line creates the SegFault
printf("%sn", s2);
}
I do not understand the subtility or my mistake. Any tips?
char *s = "..."
creates a string literal and string literals are not modifiable (and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined. (see https://en.cppreference.com/w/c/language/string_literal)