Copy results of strtok to 2 strings in C
Question
Ok, so I have the code
char *token; char *delimiter = " "; token = strtok(command, delimiter); strcpy(command, token); token = strtok(NULL, delimiter); strcpy(arguments, token);
and it gives me EXC_BAD_ACCESS when i run it, and yes, command and arguments are already defined.
Solution
Why are you copying the token into command
when you're parsing command
? It's a very unsafe thing to do.
You can do:
char *command_tok, *args_tok;
command_tok = strtok(command, delimiter);
args_tok = strtok(NULL, delimiter);
Now command_tok
and args_tok
point to the command and arguments part of the initial string, assuming it parses correctly. Note that they point to parts of the command
buffer and don't have their own allocated memory. You can safely copy from them into other buffers.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow