C segment fault for modification to string literal

Compile and run the following code, an segment fault error will occur.

 

int main(int argc, const char *argv[])
{
  char str1[] = "abc";
  *str1 = 'A';
  char * str2 = "abc";
  *str2 = 'A';
  return 0;
}
 

The reason is str2 is pointing to a string literal which is located in read-only memory. Attempting to modify read-only memory causes the segment fault. For details, refer to

 

Why does simple C code receive segmentation fault?

 

你可能感兴趣的:(C++,c,C#)