Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between strtok and strtok_r in C?

Tags:

What's the difference between strtok and strtok_r in C and when are we supposed to use which?

like image 955
dreamer_999 Avatar asked Mar 05 '14 22:03

dreamer_999


People also ask

What does strtok () do in C?

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 used?

Practical Application: strtok can be used to split a string in multiple strings based on some separators. A simple CSV file support might be implemented using this function.

Why multiple call to strtok () is not 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 .

Does strtok allocate memory?

It is important to not that strtok does not allocate memory and create new strings for each of the tokens it finds. All the data still resides in the original string. Whenever strtok is called, it continues from where it left off and skips separators until it gets a valid character.


1 Answers

strtok is equivalent to (and often defined as):

char *strtok(char *str, const char *delim) {     static char *save;     return strtok_r(str, delim, &save); } 

in general, you should use strtok_r directly rather than strtok, unless you need to make your code portable to pre-POSIX-2001 systems that only support strtok

like image 103
Chris Dodd Avatar answered Oct 27 '22 13:10

Chris Dodd