Q:

strtok() returning incorrect value in C99?

I'm running on a 32bit linux system using std c99 first off. So I have this code
char* tokPtr = strtok(expr, " ");
    while(tokPtr != NULL) {
            tokPtr = strtok(NULL, " ");
            puts(tokPtr);
            push(tokens, tokPtr);
    }

expr is a C string passed in as a parameter looking something like "1 2 +". And I'm just using puts for testing purposes. However, when I run valgrind with the --leak-check=full flag on it gives me an invalid read of size 1 for strlen in puts and ends with a seg fault. When I make tokPtr = "1"; and comment out the strtok() stuff, I run valgrind and no errors at all. I have no idea why this is happening and I could really use some help. Thanks.

A:

Here:
while(tokPtr != NULL) {
    tokPtr = strtok(NULL, " ");
    puts(tokPtr);

you should be checking whether tokPtr == NULL after you call strtok(), not before. When strtok() does finally return NULL, as it will eventually, you will always pass NULL to puts() with this code, and that's giving you your problem. 
You can just reorder, and change to:
char* tokPtr = strtok(expr, " ");
while(tokPtr != NULL) {
    puts(tokPtr);
    push(tokens, tokPtr);
    tokPtr = strtok(NULL, " ");
}

Also remember that strtok() modifies the string it works with and returns internal pointers to that string. You don't show your push() function, but unless the code is very simple, and your expr array always outlasts your stack, you're likely to run into problems pushing these pointers onto it. It may be better to malloc() some memory for each token and copy what strtok() returns into it, and then push those.

