1

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?

8
  • 1
    Note: You're executing the program, the compilation has already successfully created the a.out file. It does not segfault "during compilation". Commented Dec 20, 2012 at 11:44
  • 1
    @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. Commented Dec 20, 2012 at 12:00
  • @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. Commented Dec 20, 2012 at 12:07
  • @interjay how's this one instead ? Commented Dec 20, 2012 at 12:10
  • 1
    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. Commented Dec 20, 2012 at 13:31

2 Answers 2

6
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?;?

Sign up to request clarification or add additional context in comments.

1 Comment

And the downvote is for? Bother telling only if there is a technical reasoning.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.