This code is giving me a segmentation fault at run time.
char *str = "HELLO";
str[0] = str[2];
Please can anyone tell me why?
This code is giving me a segmentation fault at run time.
char *str = "HELLO";
str[0] = str[2];
Please can anyone tell me why?
 
    
     
    
    You cannot modify the contents of a string literal. Put it in a character array if you wish to be able to do so.
char str[] = "HELLO";
str[0] = str[2];
 
    
    You're getting a seg-fault because the compiler has placed the string constant "HELLO" into read-only memory - and attempting to modify the string is thus failing.
 
    
    This is compiled to a string literal in the read only section.
        .section        .rodata
.LC0:
        .string "HELLO"
 
    
    Standard does not allow modifying a string literal. The string is stored in a readonly segment of the program, for example in linux, it is stored in the .rodata section of the executable which cannot be written.
