Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: STRTOK exception [duplicate]

Tags:

c

string

strtok

for some reason i get an exception at the first use of strtok() what i am trying to accomplish is a function that simply checks if a substring repeats itself inside a string. but so far i havent gotten strtok to work

int CheckDoubleInput(char* input){
char* word = NULL;
char cutBy[] = ",_";

word = strtok(input, cutBy);  <--- **error line**

/* walk through other tokens */
while (word != NULL)
{
    printf(" %s\n", word);
    word = strtok(NULL, cutBy);
}
return 1;
}

and the main calling the function:

CheckDoubleInput("asdlakm,_asdasd,_sdasd,asdas_sas");

screenshot of the error im getting

like image 533
Felix Kreuk Avatar asked Dec 28 '13 09:12

Felix Kreuk


People also ask

Why is strtok segmentation fault?

Since this memory is marked as read-only, and since strtok writes into the string that you pass into it, you get a segmentation fault for writing into read-only memory.

Does strtok affect the original string?

Because strtok() modifies the initial string to be parsed, the string is subsequently unsafe and cannot be used in its original form. If you need to preserve the original string, copy it into a buffer and pass the address of the buffer to strtok() instead of the original string.

What does strtok mean in C?

Apr 07, 2007. The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.

Why is strtok not thread safe?

strtok is neither thread safe nor re-entrant because it uses a static buffer while parsing. This means that if a function calls strtok , no function that it calls while it is using strtok can also use strtok , and it cannot be called by any function that is itself using strtok .


1 Answers

CheckDoubleInput() is ok. Look at this. Hope you will understand

int main(){
    char a[100] = "asdlakm,_asdasd,_sdasd,asdas_sas";
    // This will lead to segmentation fault.
    CheckDoubleInput("asdlakm,_asdasd,_sdasd,asdas_sas");
    // This works ok.
    CheckDoubleInput(a);
    return 0;
}
like image 64
taufique Avatar answered Sep 24 '22 03:09

taufique