strtok
is kind of a strange function in that it mutates the input buffer to insert nuls, and maintains internal state.
You are generally better off avoiding strtok
and using strchr
instead. Calling strtok repeatedly on pointers into the same buffer is likely to crash.
Either way, as a general rule, functions don't reject malloc'd memory. It's a clue you have some corruption going on, whether you use malloc or not. Running your program under Valgrind or similar will make it more obvious where.
So, why specifically does it crash here?
If the line contains a #
then the first call to strtok
will replace the #
with a nul. Either way it returns a pointer to the first non-# byte of the string.
Your second call to strtok prints the string between the first and second #
which is probably not what you want.
One problem you may be having here is that strtok
returns null on lines that contain no non-delimiter characters. For example an empty line or a line with only spaces will cause token
to get set to null and then the printf will crash.
A better version (untested) would be something like this:
char *star, *token, *arg;
star = strchr(buff, '#');
if (star) *star = '\0';
token = strtok(buff, " \t");
if (!token)
continue; // empty line
printf("operator: %s\n", token);
while ((arg = strtok(NULL, " \t")) != NULL)
printf("arg: %s\n", arg);
Important things here:
- check for null ;)
- we don't use strtok to do something more easily done with strchr
- for each string, first strtok points to the buffer and gets the first word, then the rest use null
But as I said, I would strongly consider using avoiding it if the syntax is nontrivial.