Question

I'm trying to tokenize a string with multiple spaces. For example, "yes___no", where the underscores are spaces. Using strtok(string, " ");

But I am getting a seg fault and after debugging I see after I tokenize the second string is "\024\002" and when printing this incorrect string I get my error.

Was it helpful?

Solution

You cannot change a string literal.

/* does not work */
char *data = "yes no";
strtok(data, " ");

The strtok above will try to break the data at the space by writing a '\0' there: data[3] = '\0';, but string literals are not modifiable. Try instead

/* works */
char data[] = "yes no";
strtok(data, " ");

Edit: copy a string literal to a character array

char *data = "string literal";
/* ... */
char *copy;
size_t datalen = strlen(data) + 1;
copy = malloc(datalen);
if (copy != NULL) {
    strcpy(copy, data);
    /* use copy now ... strtok(copy, " "); ... or whatever you need */
    free(copy);
} else {
    /* no memory. Tell user to upgrade computer :-) */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top