1
votes

The following piece of code produces a segmentation fault during compilation:

(gdb) run
Starting program: /home/anna/Desktop/a.out
Program received signal SIGSEGV, Segmentation fault.
0xb7e97845 in strtok () from /lib/i386-linux-gnu/libc.so.6

#include <string.h>
#include <stdio.h>

main () {
char * sentence = "This is a sentence.";
char * words[200] ;
words[0] = strtok(sentence," ");
}

After changing the 5th line, no error is thrown.

#include <string.h>
#include <stdio.h>

main () {
char  sentence[] = "This is a sentence.";
char * words[200] ;
words[0] = strtok(sentence," ");
}

Why is this happening?

2
Note: You're executing the program, the compilation has already successfully created the a.out file. It does not segfault "during compilation".unwind
@WhozCraig This is not a duplicate of that question - the code in the linked question is not actually writing to a string literal, despite the title.interjay
@interjay good point. this question is asked at least a couple of times a day. you would think it would be easily findable among the dupes. i'll keep searching. thanks.WhozCraig
@interjay how's this one instead ?WhozCraig
Welcome to SO. It should be int main(void). Generally I have the idea that first reading a bit about C could help you a lot.Jens Gustedt

2 Answers

2
votes

Read the man page of strtok (BUGS section),

  • These functions modify their first argument.
  • These functions cannot be used on constant strings.

and char *sentence = "This is a sentence"; is allocated in read-only context, so treated as contant.

6
votes
char * sentence = "This is a sentence.";

sentence is a pointer pointing to a string literal "This is a sentence." is stored in a read only memory and you should not be modifying it.
Modifying a string literal in any way results in Undefined Behavior and in your case it manifests in a segmentation fault.

Good Read:
What is the difference between char a[] = ?string?; and char *p = ?string?;?