4

I am trying to read data from a file, tokenize it and sort it, however strtok behaves erratically when I run it, sometimes it works sometimes it doesn't and I get very short/odd tokens.

Valgrind seems to think it is because strtok is relying on an uninitialised value (I think):

==7069== Conditional jump or move depends on uninitialised value(s)  
==7069==    at 0x40B61A3: strtok (strtok.S:160)  
==7069==    by 0x8048842: main (main.c:58)

Here is the function that I think valgrind is accusing:

char * getNextToken(char * line) {  
    char delim = ',';  
    return strtok(line, &delim);  
}

Could this be because line is NULL for most of my calls to strtok?

Here are my calls to the function:

strcpy(performer, getNextToken(inputLine));  
strcpy(title, getNextToken(NULL));  
strcpy(charMin, getNextToken(NULL));  
/*etc...*/

I have no idea what could be causing this and all the values I give strtok are what I am expecting. Also I will occasionally get a stack smashing error, I don't know why.

L. F.
  • 19,445
  • 8
  • 48
  • 82
jrisebor
  • 70
  • 9

2 Answers2

7

strtok takes a null-terminated string for both arguments. You're not passing one for your delimiter. try this:

char * getNextToken (char * line){
    const char *delim = ",";
    return strtok(line, delim);
}
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

First answer has it right regarding strtok(). But beyond that, and possibly why you're getting "stack smashing errors", is because strtok will return a pointer to whatever token it finds, and if that's bigger than the array you've allocated for the destination for strcpy(), it will happily overflow it.

I would consider using strdup() instead of strcpy().

malcolmpdx
  • 4,132
  • 1
  • 16
  • 7