Segmentation error Strtok_r

I know this was asked before, but the previous answers said that you cannot change the string literal, and if I am not mistaken, it is not. I can successfully use strtok_r to the very last line of input, then I get a seg error. Why is this going to happen? Heres a simplified version of my code. From printing, I know that it is processed through get b, but then is there a seg error?

#include <stdio.h>
#include <string.h>   //strlen
#include <stdlib.h>

    void handler(char * input){
    char * end_str;
    char * token =strtok_r(input, "\n", &end_str);
    char * endd_str;
    char * token2= strtok_r(token, " ", &endd_str);
    while(token!=0){
        printf("%s\n",token);
        token=strtok_r(NULL,"\n",&end_str);
        while(token2 !=0){
            token2 =strtok_r(NULL," ",&endd_str);
            printf("%s\n",token2);}
    }

}

int main(int argc , char *argv[])
{
    char test[100]="set a,10.5\nset b,11.5\nget b\nadd e,a,b\nsub g,a,b";
    handler(test);
    return 0;
}
+4
source share
2 answers

strtok_r , . while token2 =strtok_r(NULL," ",&endd_str);, endd_str , , strtok_r NULL. NULL printf segfault.

"\n" " ". , . , strtok_r , while .

:

void handler(char * input){
    char * end_str;
    char * token =strtok_r(input, "\n", &end_str);
    while(token!=0){
        printf("%s\n",token);
        char * endd_str;
        char * token2= strtok_r(token, " ", &endd_str);
        while(token2 !=0){
            printf("%s\n",token2);
            token2 =strtok_r(NULL," ",&endd_str);    // call at end of loop
        }
        token=strtok_r(NULL,"\n",&end_str);          // call at end of loop
    }
}

Ouput:

set a,10.5
set
a,10.5
set b,11.5
set
b,11.5
get b
get
b
add e,a,b
add
e,a,b
sub g,a,b
sub
g,a,b
+2

(MS Visual ++). strtok_s strtok_r, , Windows POSIX.

.

#include <string.h>   //strlen
#include <stdlib.h>

void handler(char * input){
    char * end_str;
    char * token =strtok_s(input, "\n", &end_str); // tokenize input string
    char * endd_str;
    char * token2 = NULL;

    while(token!=0){

        printf("%s\n",token);

        token2 = strtok_s(token, " ", &endd_str); // retokenize first token
        while(token2 !=0){
            printf("%s\n",token2); // replace printf call to avoid null string output and first token miss
            token2 =strtok_s(NULL," ",&endd_str);}

        token = end_str; // "important" restore char pointer to point the last untokenized input character

        token=strtok_s(token,"\n",&end_str); // the same as printf issue is for all loops body
    }

}

int main(int argc , char *argv[])
{
    char test[100]="set a,10.5\nset b,11.5\nget b\nadd e,a,b\nsub g,a,b";
    handler(test);
    return 0;
}
+1

Source: https://habr.com/ru/post/1620394/


All Articles