-2

strtok() is crashing. It works in main(), but not in the call function. Please advise me. Thank you.

int checkNumberOfTokens (char* text, char* delimitChar) {

    int numberOfTokens = 0;
    char *t;
    int i;

    printf("Text: %s\n", text);  
    printf("delimitChar: %s\n", delimitChar);

    t = strtok(text, delimitChar);

    for (i=0; t != NULL; i++) {
        printf("token %d is \"%s\"\n", i, t);
        t = strtok(NULL, delimitChar);
        }

        numberOfTokens = i;
        printf("Total number of tokens: %d\n", numberOfTokens);    

        return numberOfTokens;
}




int main()

    char* transitionTable[] = {
                              "NA, NA, NA, NA, NA, NA",
                              "defaultStart, elseOther, 1, 2, 6, NA",

          };

          printf("%s \n", transitionTable[1]);

    char delimitChar[] = ",";

    checkNumberOfTokens (transitionTable[1], delimitChar);
Ursa Major
  • 851
  • 7
  • 25
  • 47

2 Answers2

3

strtok input string has to be writable as strtok modifies the input string. But you are passing a string literal and string literals are non modifiable.

See c-faq on string literals:

http://c-faq.com/decl/strlitinit.html

ouah
  • 142,963
  • 15
  • 272
  • 331
2

PROBLEM: You're passing in a string literal (read-only); but strtok() expects to be able to modify the string.

SUGGESTION: try strchr() instead of strtok().

EXAMPLE:

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

int
checkNumberOfTokens (char * text, char delimitChar) 
{
  char *s = text;
  int ct = 1;
  if ((s == NULL) || (strlen(s) == 0))
    return 0;

  while ((s = strchr(s, delimitChar))) {
    s++;
    ct++;
  }
  return ct;
}

int main(int argc, char *argv[]) 
{
   int ct = checkNumberOfTokens("ABC,DEF,GEHI", ',');
   printf ("ct=%d\n", ct);
   return 0;
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190