csegmentation-faultcstringc-stringskr-c

Writing into c-string


my code segfaults and I don't know why.

 1  #include <stdio.h>
 2
 3  void overwrite(char str[], char x) {
 4    int i;
 5    for (i = 0; str[i] != '\0'; i++)
 6      str[i] = x;
 7  }
 8
 9  int main(void) {
10    char *s = "abcde";
11    char x = 'X';
12    overwrite(s, x);
13    printf("%s\n", s);
14    return 0;
15  }

The gdb debugger tells me, that problem is on the line 6, where I want to store a char, into c-string (if I use lvalue pointer dereferencing, it's the same problem.) This is what he says:

(gdb) run
Starting program: /tmp/x/x 

Breakpoint 1, overwrite (str=0x8048500 "abcde", x=88 'X') at x.c:5
5         for (i = 0; str[i] != '\0'; i++)
(gdb) s
6           str[i] = x;
(gdb) 

Program received signal SIGSEGV, Segmentation fault.
0x080483e3 in overwrite (str=0x8048500 "abcde", x=88 'X') at x.c:6
6           str[i] = x;
(gdb) q

I am learning from K&R-C book and this is simplified example from chapter 2.8 (the remove function). I have no idea where is the problem.


Solution

  • because char*s = "abcde"; creates string in readonly memory. try

    char s[] = "abcde";
    

    EDIT: explanation: char* is pointer, and "abcde" is created in readonly memory -> immutable.

    char[] is array, which is wholly stored on stack and initialized from the memory, so is mutable