why a string array cannot be rewroten

Hello,

Have you guys any idea why the following code leads to a segmentation fault (access violation)?

#include <stdio.h>
char * Portho[7] = {"SIGE","E","G12","G13","G23","RHO","ALPHA"};
int main() {
Portho[0][0] = 'S';
return 0;
}


Moreover, when I move char * Portho[7] = {"SIGE","E","G12","G13","G23","RHO","ALPHA"}; into main, the program compiled with microsoft cl runs without problem; but the code compiled by gcc still gives a segmentation fault.

Thank you for your help in advance.
To remove unnecessary parts, the same problem would be with
1
2
3
4
int main(){
   char* str = "hello";
   str[0] = 'x';
}
The thing is that the type of a string literal is really a const char* meaning that its chars can't be altered. I have no clue why C++ allows to drop that const in this case. The const is there so that the compiler doesn't have to allocate new strings every time you write "hello". Now every time you write "hello" a pointer to the same string can be returned.
As for different compilers acting differently, I guess this is undefined behavior.
Last edited on
Quoting from the C++ Standard 2003 (I don't have a copy of the 2011 issue yet):

A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes,

so what you've got there are string literals. The next important bit (after, as the hamsterman says, an ordinary string literal has type “array of n const char) is (as the hamsterman guessed):

The effect of attempting to modify a string literal is undefined.

This means that when you try to change it, anything could happen. Anything. Relying on undefined behaviour is dangerous, and it's not recommended.

Topic archived. No new replies allowed.