How to use strtok in C properly so there is no memory leak?

Posted by user246392 on Stack Overflow See other posts from Stack Overflow or by user246392
Published on 2011-02-15T05:42:40Z Indexed on 2011/02/15 7:25 UTC
Read the original article Hit count: 127

Filed under:
|
|
|

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
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about malloc