Who throws a segmentation error?

Given the program below.

 int main() {
 char *str = "hello word";
 str[0] = 'a';
 return 0;
 }

The above program throws a segmentation error. I know this is thrown away because the read-only segment contains the world hello and cannot be changed. If an instruction is written in the L1 cache (inside the processor), which changes from "h" to "a", and the MMU gets into the image only when the page is reset from L3 to the main memory, which eliminates the segmentation error almost immediately.

The code below that does the same does not cause any segmentation error. Why?

 int main() {
 char str[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};
 str[0] = 'a';
 return 0;
 }
+3
source share
2 answers

, , , , . , () ; , .

, : . undefined. char, , . , .

+3

, . .

char str[] = {'h','e','l','l','o',' ','w','o','r','l','d','\0'};

str - , . str . -

char *str = "hello word";

str , . , .


, C ++ . ISO/IEC 14882: 2003 (E), 8.5.2

1. A char array (whether plain char, signed char, or unsigned char) can be 
   initialized by a string- literal (optionally enclosed in braces); a wchar_t 
   array can be initialized by a wide string-literal (option- ally enclosed in 
   braces); successive characters of the string-literal initialize the members of 
   the array.

     [Example:
           char msg[] = "Syntax error on line %s\n"; shows a character array 
           whose members are initialized with a string-literal. Note that because 
           ’\n’ is a single character and because a trailing ’\0’ is appended, 
           sizeof(msg) is 25. 
     ] 

2. There shall not be more initializers than there are array elements. 

    [Example:
          char cv[4] = "asdf" ;// error is ill-formed since there is no space for the implied trailing ’\0’. 
    ]

, 2 .

+2

Source: https://habr.com/ru/post/1795401/


All Articles