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");
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.
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.
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.
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 .
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With