我是否需要释放strtok结果字符串?

或者更确切地说,strtok如何生成它的返回值指向的字符串? 它是否动态分配内存? 我问,因为我不确定是否需要在以下代码中释放令牌:

STANDARD_INPUT变量用于退出过程,以防我内存耗尽以进行分配,字符串是测试对象。

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 } 

strtok操纵您传入的字符串并返回指向它的指针,因此不会分配任何内存。

请考虑使用strsep或至少strtok_r以便以后节省一些麻烦。

根据文件 :

回报价值

指向字符串中找到的最后一个标记的指针。

由于返回指针只指向输入字符串中令牌开始的字节之一,因此是否需要释放取决于您是否分配了输入字符串。

strtok(…)函数的第一个参数是你的字符串:

海峡
C字符串要截断。 请注意,此字符串通过分解为较小的字符串(标记)进行修改。 或者,可以指定空指针,在这种情况下,该函数继续扫描先前成功调用该函数的位置。

它将’\ 0’字符放入您的字符串中,并将它们作为终止字符串返回。 是的,它破坏了你的原始字符串。 如果您以后需要,请复制一份。

此外, 它不应该是常量字符串 (例如char* myStr = "constant string";). 看到这里 。

它可以在本地分配,也可以通过malloc / calloc分配。

如果你在堆栈上本地分配它(例如char myStr[100]; ),则不必释放它。

如果你通过malloc分配它(例如char* myStr = malloc(100*sizeof(char)); ),你需要释放它。

一些示例代码:

 #include  #include  int main() { const char str[80] = "This is an example string."; const char s[2] = " "; char *token; /* get the first token */ token = strtok(str, s); /* walk through other tokens */ while( token != NULL ) { printf( " %s\n", token ); token = strtok(NULL, s); } return(0); } 

注意:此示例显示了如何遍历字符串…由于您的原始字符串被破坏,strtok(…)会记住您上次的位置并继续处理字符串。