2

So for the last several hours I have been trying to figure out why I was getting a seg fault while printing a freshly tokenized string using strtok(). FINALLY I realized I was not including string.h. After adding this line, I get the expected behaviour and no more seg fault... yay! However, I am new to c (although not programming) if someone could please explain the behaviour I was experiencing and answer the following...

  1. Why was I not receiving an error when calling strtok() when it was not included?
  2. I read recently that if you do not include the string.h, the default method signature will be used. However, I want to use strtok()'s default sig so why am I still getting this undefined behaviour?

    char    str[]= "ls -l";    
    char *  p    = strtok (str, " ");
    
    printf ("%s\n",p);
    

Seg fault on the last line

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Callback Kid
  • 708
  • 5
  • 22

1 Answers1

2

The problem is implicit function declaration, you should use warnings to prevent that.

The segmentation fault was because the compiler thought that strtok() was returning an integer, so you was assigning a signed integer to a pointer, and then trying to dereference the pointer, which is Undefined Behavior and can result in a segmentation fault.

Also never try to access the returned pointer from strtok() without checking if it's NULL first

char  str[] = "ls -l";    
char *p     = strtok (str, " ");

if (p != NULL)
    printf ("%s\n", p);

because it returns NULL when no token is found.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97