Reputation: 6665
I am trying to use strtok()
to parse a string deliminated by spaces. From what I can tell, I am using it correctly, but it won't run on ideone.com. Is there anything wrong with the following code? I just get Runtime error time: 0 memory: 2288 signal:11
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static void test(char *command)
{
char* output = strtok(command, " ");
printf("%s\n", output);
}
int main(void) {
test("set_rate 200");
return 0;
}
Here it is on ideone.com if you want to try it.
Upvotes: 4
Views: 1695
Reputation: 10516
When you pass hard coded string that was stored in read-only memory.
strtok()
does not work with string which is read-only memory.
You need to use string variable rather than string literal .
you can first store string in some variable and then you can pass it to the function.
char[]="set_rate 200";
test(str);
See example:
char *str = malloc(20);
char *tok = NULL;
int len = 0;
strcpy(str, "This is a string");
len = strlen(str);
printf("string before strtok(): %s\n", str);
tok = strtok(str, " ");
while (tok) {
printf("Token: %s\n", tok);
tok = strtok(NULL, " ");
}
Edit
From @Yu Hao comment i am adding this
char *str = "set_rate 200";
test(str); // This won't work. here str is pointer to the string literal.
Upvotes: 2
Reputation: 137467
Always consult the man
pages first.
strtok(3)
says:
Be cautious when using these functions. If you do use them, note that:
These functions modify their first argument.
These functions cannot be used on constant strings.
Upvotes: 4
Reputation: 122433
strtok
will modify the string passed as the first parameter, so you can't pass a string literal, change your main
like this:
int main(void) {
char str[] = "set_rate 200";
test(str);
return 0;
}
str
here is an char
array, but not a string literal.
Upvotes: 3
Reputation: 7112
As strtok
modifies the string, it requires that the string is not in read-only memory. So when you pass a string literal to your test function, it crashes.
This is better:
char s[] = "set_rate 200";
test(s);
Upvotes: 3