Question

I get segmentation fault with the following code using strtok. Am I using strtok correctly?

int main()
{
    dummy("90:90");
    return 0;
}
int dummy(char *str)
{
    char *mm, *hh;
    int len = strlen(str), result;

    if (len <= 0 || len > 5)
    {
            return 0;
    }

    hh = strtok(str, ":");

    while(hh){
        printf("%s", hh);
        hh = strtok(NULL, ":");
    }

return result;
}
Was it helpful?

Solution 2

you can not use strtok() with a constant string. And that what you did in your code.

Because the strtok() edit the string and the constant strings are a read only strings.

To fix your problem, Duplicate your string in a dynamic allocated memory (read-write memory) in this way:

int dummy(char *str)
{
    char *mm, *hh;
    int len = strlen(str), result;

    if (len <= 0 || len > 5)
    {
            return 0;
    }

    char *buf = strdup(str); // Modif here


    hh = strtok(buf, ":"); // Modif here

    while(hh){
        printf("%s", hh);
        hh = strtok(NULL, ":");
    }

    free(buf); // Modif here

    return result;
}

OTHER TIPS

strtok modified the content of its argument, so you can't pass a string literal. Change it to:

int main()
{
    char str[] = "90:90";
    dummy(str);
    return 0;
}

When function strtok is called with the first argument being a string which is not NULL, it changes the contents of that string, so that in the following calls (with NULL) it will be able to fetch the next token.

You, however, are passing a constant string which resides in the (read-only) code-section of your program. So during run-time, the CPU attempts to write into a read-only memory section, leading to an illegal memory access.

In short, you need to declare the string as a local array in the stack of function main:

int main()
{
    char str[] = "90:90";
    dummy(str);
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top