Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?

The following code receives seg fault on line 2:

char *str = "string"; str[0] = 'z';  // could be also written as *str = 'z' printf("%s\n", str); 

While this works perfectly well:

char str[] = "string"; str[0] = 'z'; printf("%s\n", str); 

Tested with MSVC and GCC.

like image 234
Markus Avatar asked Oct 02 '08 19:10

Markus


People also ask

How do I find out what is causing my segmentation fault?

Check shell limits Usually it is the limit on stack size that causes this kind of problem. To check memory limits, use the ulimit command in bash or ksh , or the limit command in csh or tcsh . Try setting the stacksize higher, and then re-run your program to see if the segfault goes away.

Why am I getting segmentation faults C++?

A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program. Used to being properly initialized.

What causes segmentation fault with pointers?

A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.


1 Answers

See the C FAQ, Question 1.32

Q: What is the difference between these initializations?
char a[] = "string literal";
char *p = "string literal";
My program crashes if I try to assign a new value to p[i].

A: A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

  1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).
  2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element.

Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

like image 195
matli Avatar answered Oct 04 '22 01:10

matli