segfault at c-string

1
2
3
4
5
6
7
8
9
#include <cstdio>

int main()
{
    const char * const  name = "Rod";
    char * ptr = (char*)name;
    *ptr = 'T';
    std::printf( "%s\n", name );
}


At this, I expected that the first char of the storage address of 'name' would be changed to 'T'. But all I get is a segfault. The c-string 'name' should reside at some storage address of the program code.

Any idea why it comes here to a segfault?
Taking a const T * (i.e. a pointer to constant data), casting it to T * (a pointer to non-constant data), and then writing to the casted pointer results in undefined behavior.
Most implementations store string literals in a read-only region of the binary, which when the program runs is loaded to read-only memory. Any attempt to write to that memory will crash the program.

You can accomplish what you wanted (somewhat) like this:
1
2
3
char name[] = "Rod";
name[0] = 'T';
std::cout << name << std::endl;
Thanks, that makes sense.
Topic archived. No new replies allowed.