Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to free the strtok resulting string?

Tags:

Or rather, how does strtok produce the string to which it's return value points? Does it allocate memory dynamically? I am asking because I am not sure if I need to free the token in the following code:

The STANDARD_INPUT variables is for exit procedure in case I run out of memory for allocation and the string is the tested subject.

int ValidTotal(STANDARD_INPUT, char *str) {     char *cutout = NULL, *temp, delim = '#';     int i = 0; //Checks the number of ladders in a string, 3 is the required number     temp = (char*)calloc(strlen(str),sizeof(char));     if(NULL == temp)         Pexit(STANDARD_C); //Exit function, frees the memory given in STANDARD_INPUT(STANDARD_C is defined as the names given in STANDARD_INPUT)     strcpy(temp,str);//Do not want to touch the actual string, so copying it     cutout = strtok(temp,&delim);//Here is the lynchpin -      while(NULL != cutout)     {         if(cutout[strlen(cutout) - 1] == '_')             cutout[strlen(cutout) - 1] = '\0'; \\cutout the _ at the end of a token         if(Valid(cutout,i++) == INVALID) //Checks validity for substring, INVALID is -1             return INVALID;         cutout = strtok(NULL,&delim);         strcpy(cutout,cutout + 1); //cutout the _ at the beginning of a token     }     free(temp); return VALID; // VALID is 1 } 
like image 575
Sunspawn Avatar asked Jan 03 '14 12:01

Sunspawn


People also ask

Do you have to free after strtok?

If you allocated it locally on the stack (e.g. char myStr[100]; ), you don't have to free it. If you allocated it by malloc (e.g. char* myStr = malloc(100*sizeof(char)); ), you need to free it.

What does strtok do to the original string?

Because strtok() modifies the initial string to be parsed, the string is subsequently unsafe and cannot be used in its original form. If you need to preserve the original string, copy it into a buffer and pass the address of the buffer to strtok() instead of the original string.

Does strtok affect string?

strtok() breaks the string means it replaces the delimiter character with NULL and returns a pointer to the beginning of that token. Therefore after you run strtok() the delim characters will be replaced by NULL characters.

Does strtok include the delimiter?

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte.


1 Answers

strtok manipulates the string you pass in and returns a pointer to it, so no memory is allocated.

Please consider using strsep or at least strtok_r to save you some headaches later.

like image 198
Andreas Avatar answered Sep 20 '22 13:09

Andreas