cpointersundefined-behaviorstrtokinvalid-pointer

C free variables used with strtok


I already saw post similar to this one, but I found a little difference that drive me in the wrong way.

I have this code:

char * token_one = strtok(my_buffer, " ,.-");
char * token_two = strtok(NULL, " ,.-");

free(token_one);
free(token_two);

I saw post where people says a variable used with strtok should not be freed but why while executing this code I get this:

free(token_one) no errors

free(token_two) I get "invalid pointer"

Why don't I get error in free(token_one)? What is the correct way to handle this?


Solution

  • If you look how strtok() works, it becomes immediately clear:

    1. The first call to strtok() returns the given pointer, modifying the string pointed to by it by replacing the next separation character with a NUL byte.
    2. Any subsequent call, done with NULL as the first argument, operates on the saved pointer from before which points to one after the replaced character.

    So the first free() call succeeds iff your my_buffer came from malloc(). The second one fails because, well, why shouldn't it? It doesn't come from malloc() et al., so calling free() on it is undefined behaviour.