From where did you get the idea that you need to free(token)
and free(tk)
? You don't. strsep()
doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc()
(or similar), so free()
ing them is undefined behavior. You only need to free(s)
when you are done with the entire string.
Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup()
and free()
altogether by simply writing char *s = p;
.