0

So I have a string with multiple newline escape sequences within it. I would like to cut the string to the first n lines, like the head program from coreutils. For example say I have the string "a\nb\nc\n", I would want the first line so I would want my output string to be "a". In other cases where I needed to cut a string I simply placed a null terminator in the position where I wanted the string to end. However when I run something like this:

void main() {
    char *str = "a\nb\nc\n";
    str[1] = '\0';
}

I get a segfault. I really don't understand why. What can I do to fix this?

Alex Wicks
  • 55
  • 6
  • 4
    You can't modify string literals. You need an array `char str[] = "a\nb\nc\n";`. More precisely, any attempt to modify a string literal leads to undefined behaviour, and the most frequent expression of this specific subspecies of undefined behaviour is a segmentation fault and crash. – Jonathan Leffler Jun 13 '18 at 04:37
  • Thanks! That seems to work fine. Why does that work, whereas my example doesn't? – Alex Wicks Jun 13 '18 at 04:39
  • 1
    Typically, the string literals are stored in a read-only memory segment, so any attempt to modify them attempts to subvert the memory protection provided by the o/s, and the o/s takes a dim view of such attempts. When you use an array, it's modifiable like any other variable. You should strictly use `const char *str = "a\n";` but historical code (from before there was a C standard) didn't use `const` (it was added to the standard), so the standard couldn't mandate it. Note that string literals may share the same space, so modifying one could modify many — whereas arrays are defined separately. – Jonathan Leffler Jun 13 '18 at 04:43
  • Thanks for the thorough answer, that makes a lot of sense now I know that's what's happening! – Alex Wicks Jun 13 '18 at 04:52

0 Answers0