Question

I am attempting to take a line of user input from stdin using fgets, tokenize it with strtok, and then print each token to make sure it was tokenized correctly. My code is as follows:

char buffer[256];
char *token;`
fgets(buffer, 256, stdin);
token=strtok(buffer," \n\t()<>|&;");

while(token!=NULL) {
        printf("%s",token);
        count++;
        token = strtok(NULL," \n\t()<>|&;");
}

I get a segmentation fault whenever I get to the printf call, however, and I can't seem to figure out exactly why.

Was it helpful?

Solution 2

Okay, I changed your code into a complete program, cf:

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

int main() {
    char buffer[256];
    char *token;
    int count = 0;
    fgets(buffer, 256, stdin);
    token=strtok(buffer," \n\t()<>|&;");

    while(token!=NULL) {
        printf("%s\n",token);
        count++;
        token = strtok(NULL," \n\t()<>|&;");
    }
    return 0;
}

when I run it in it's original form it works

bash $ ./a.out
the quick brown fox
thequickbrownfoxbash $ 

Although of course there are no spaces or newlines. When I add the \n, (as in code above) I get

bash $ ./a.out
the quick brown fox
the
quick
brown
fox
bash $ 

Now, note that I had to remove your back-tick (I assume it was a typo) and I had to declare your count variable, but given that it works.

From this I deduce that you probably have code around the fragment you showed us that's at fault.

OTHER TIPS

I don't see a problem with your code (aside from the stray ` at the end of the second line, which I assume isn't in your actual code).

However, this line:

        printf("%s",token);

will never print any newline, which means that it will never flush the output buffer. So if you have a segmentation fault later in your program, it might look like it's happening before you print the first token, simply because it prevents the output buffer from ever being flushed.

For debugging purposes, try changing the above to this:

        printf("%s\n",token);

and seeing what gets printed before the segfault.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top