JustMe
JustMe

Reputation: 41

strtok() and segmentation fault

I have a case, when I type "1111:2222" and "1111:" or ":2222".

When it is "1111:2222" - I just print it.

When it is "1111:" - I need to set a default value for b = 0 or for the case, when it is :2222 for a = 0.

Please, how should I handle this case? (I have only one : symbol, I handled that condition, don't show it because it is not important)

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

int main () {
   char str[80] = "11111:";
   const char s[2] = ":";
   char *token;
   int a = 0;
   int b = 0;


   /* get the first token */
    token = strtok(str, s);
    a = atoi(token);
    printf( " %s\n", a );

    /* get the second token */
    token = strtok(NULL, s); // Here is seg.fault
    if (token != NULL)
        b = atoi(token);
    else    
        b = 0;

    printf( " %s\n", b );
   return(0);
}

Upvotes: 0

Views: 141

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The cause of Segmentation Fault is that integer values are passed to %s format for printf(). Then printf() interprets the numbers as pointers that point at strings. They are actually not pointers but (in this case small) integers, so readings of strange location happens and this fire Segmentation Fault.

After resolving this by changing %s to %d or some other formats that take integers, this code will fail to handle :2222 case and assign 2222 to a, not b as desired. This is because strtok() drops prefix characters that are contained in the separators. Therefore, it seems you have to check if the first character is : yourself to handle this case.

Upvotes: 6

Related Questions