我需要释放strtok结果字符串吗? [英] Do I need to free the strtok resulting string?
问题描述
或者更确切地说,strtok如何产生其返回值指向的字符串?是否动态分配内存?我问是因为我不确定是否需要在以下代码中释放令牌:
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:
STANDARD_INPUT变量用于退出过程,以防万一我的内存不足以进行分配并且字符串是经过测试的主题.
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
}
推荐答案
strtok 处理输入的字符串并返回指向该字符串的指针, 因此没有分配内存.
strtok manipulates the string you pass in and returns a pointer to it, so no memory is allocated.
请考虑使用 strsep 或至少使用 strtok_r ,以免日后头疼.
Please consider using strsep or at least strtok_r to save you some headaches later.
这篇关于我需要释放strtok结果字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!