【发布时间】:2014-01-21 03:41:40
【问题描述】:
或者更确切地说,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
}
【问题讨论】:
-
不要,不需要,因为它返回了
temp部分的地址,对于strtok而言的代码。由free(temp)释放的温度