Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtok behaving inconsistently

Tags:

c

valgrind

strtok

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.

like image 620
jrisebor Avatar asked Feb 24 '23 21:02

jrisebor


2 Answers

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);
}
like image 184
Fred Larson Avatar answered Mar 06 '23 21:03

Fred Larson


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().

like image 26
malcolmpdx Avatar answered Mar 06 '23 20:03

malcolmpdx