C 我需要释放strtok结果字符串吗?
或者更确切地说,strtok如何生成其返回值指向的字符串?它是否动态分配内存?我这样问是因为我不确定是否需要在以下代码中释放令牌: 标准_输入变量用于退出过程,以防分配内存不足,且字符串是测试对象C 我需要释放strtok结果字符串吗?,c,free,strtok,C,Free,Strtok,或者更确切地说,strtok如何生成其返回值指向的字符串?它是否动态分配内存?我这样问是因为我不确定是否需要在以下代码中释放令牌: 标准_输入变量用于退出过程,以防分配内存不足,且字符串是测试对象 int ValidTotal(STANDARD_INPUT, char *str) { char *cutout = NULL, *temp, delim = '#'; int i = 0; //Checks the number of ladders in a string, 3 i
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 或至少<强> Strtokrr 来为您解决一些头痛问题。
< P> Strtok(…)函数的第一个参数是<>强>您的<强>字符串: str要截断的C字符串。请注意,此字符串由 被分成更小的字符串(令牌)。或者,一个空的 可以指定指针,在这种情况下,函数将继续 扫描上次成功调用函数的结束位置 它将“\0”字符放入您的字符串中,并将其作为终止字符串返回是的,它会损坏原始字符串。如果以后需要,请复制一份。 此外,它不应该是常量字符串(例如,
char*myStr=“常量字符串”)。
请参阅
它可以在本地分配,也可以由malloc/calloc分配
如果您在堆栈上本地分配了它(例如,char myStr[100];
),则不必释放它
如果您是通过malloc分配的(例如,char*myStr=malloc(100*sizeof(char));
),您需要释放它
一些示例代码:
#include <string.h>
#include <stdio.h>
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);
}
#包括
#包括
int main()
{
const char str[80]=“这是一个示例字符串。”;
常量字符s[2]=“”;
字符*令牌;
/*获取第一个令牌*/
令牌=strtok(str,s);
/*浏览其他代币*/
while(令牌!=NULL)
{
printf(“%s\n”,标记);
令牌=strtok(空,s);
}
返回(0);
}
注意:此示例显示了如何遍历字符串…由于原始字符串已损坏,strok(…)会记住您上次在哪里并继续遍历字符串。不需要,因为它会将
temp
部分的地址以代码的形式返回给strok。free(temp)
strtok释放的温度不可重入