It is well known that one must not modify string literals in C. The spec(section 6.4.5-7) clearly mentions that modifying a string literal is undefined behaviour. Trying to do so with GCC results in a segfault as the literals get stored in read-only memory.
However the following code seems to work fine with GCC.
int main() {
int *arr = (int[]){1,2,3};
arr[1] = 100;
printf("arr[1]: %i\n", arr[1]);
}
Looking at section 6.5.2.5.-5 of the spec, shows that arr
would have an automatic storage duration, similar to if I had declared int arr[] = {1,2,3};
instead.
Is there a reason why string literals are handled differently?