Supernormal Supernormal - 1 year ago 117
C Question

Segmentation fault in c-string assignment

What is wrong woth the following minimal example of string assignment? After compiling this with gcc, I get a segmentation fault when doing the assignment

string1[1] = 'x';
But I cannot understand why.

#include <stdio.h>

int main( int argc, char** argv )
char* string1 = "hello";

printf( "%s\n", string1 );
string1[1] = 'x';
printf( "%s\n", string1 );

return 0;

Answer Source

string1 is a read only string literal.

Really you should assign it to a const char*.

The behaviour on attempting to modify it (using string1[1] = 'x';) is undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download