Error using char pointer instead of char array

Possible duplicate:
Why does simple C code get a segmentation error?

I work in Ubuntu using the GCC compiler with the C language; I have this program:

void foo(char *word) { //something stupid *word = 'z'; } int main() { char word1[] = "shoe"; char *word2 = "shoe"; foo(word1); printf("%s", word1); foo(word2); printf("%s", word2); } 

And what's the difference? With the latter, I get a segmentation fault error.

+4
source share
3 answers

char word1[] = "shoe"; creates an array of 5 characters and copies the string literal "shoe" into it (which can be changed).

char *word2 = "shoe"; creates a pointer to the string literal "shoe" (which cannot be changed).

+3
source

The difference is that the first one is valid code, while the behavior of the second is undefined (since you are not allowed to change the string literal). See the FAQ .

+5
source

The problem is that your char *word2 = "shoe"; stored in the .rodata section:

 $ readelf -p .rodata adum String dump of section '.rodata': [ 4] shoe [ 9] %s 

(This would be easier to see if you saved shoe in one variable and foot in another variable.)

The compiler is allowed to store the string constant in read-only memory, since the standard does not allow changing string literals.

Your first case is an explicitly initialized array of characters; the standard allows you to change them, so they are not saved in a read-only section.

+1
source

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


All Articles