How to use strtok in C properly so there is no memory leak?
- by user246392
I am somewhat confused by what happens when you call strtok on a char pointer in C. I know that it modifies the contents of the string, so if I call strtok on a variable named 'line', its content will change. Assume I follow the bellow approach:
void function myFunc(char* line) {
// get a pointer to the original memory block
char* garbageLine = line;
// Do some work
// Call strtok on 'line' multiple times until it returns NULL
// Do more work
free(garbageLine);
}
Further assume that 'line' is malloced before it is passed to myFunc. Am I supposed to free the original string after using strtok or does it do the job for us? Also, what happens if 'line' is not malloced and I attempt to use the function above? Is it safer to do the following instead? (Assume the programmer won't call free if he knows the line is not malloced)
Invocation
char* garbageLine = line;
myFunc(line);
free(garbageLine);
Function definition
void function myFunc(char* line) {
// Do some work
// Call strtok on 'line' multiple times until it returns NULL
// Do more work
}