0

Consider the following program

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

int main() {
    char *str = "This is a test.";
    char *token;

    token = strtok(str," ");
}

It will segfault. But if I change *str to, say, str[80], it doesn't. Why is this?

Thanks

DJames
  • 571
  • 3
  • 17
  • Do you know the difference between an array and a pointer? – user253751 Jan 13 '16 at 23:49
  • Yes. Are you saying *str fails because it is a pointer, while str[] is an array? [This link](http://www.lysator.liu.se/c/c-faq/c-2.html) says "Since arrays decay immediately into pointers, an array is never actually passed to a function.". This lead me to believe that, in both cases, I am passing a pointer to strtok. – DJames Jan 14 '16 at 15:09
  • Yes. However in the working case you are passing a pointer to *your array*, and in the non-working case you are passing a pointer to *a string literal*. – user253751 Jan 14 '16 at 20:07

1 Answers1

3

The trouble is that the type is wrong.

char *str = "This is a test.";

It may say char* but the thing on the right is actually char const* (C is very lax in allowing type punning (is that correct word)). Any attempt to modify a const is undefined behavior.

The function strtok() actually modifies the underlying string (by inserting '\0') so this is undefined behavior.

Fix by doing.

char str[] = "This is a test.";
Martin York
  • 257,169
  • 86
  • 333
  • 562