【问题标题】:Do I need to free the strtok resulting string?我需要释放 strtok 结果字符串吗?
【发布时间】: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)释放的温度

标签: c free strtok


【解决方案1】:

strtok 操作你传入的字符串并返回一个指向它的指针, 所以没有分配内存。

请考虑使用 strsep 或至少 strtok_r,以免日后麻烦。

【讨论】:

  • strtok 不可重入
【解决方案2】:

strtok(...) 函数的第一个参数是 YOUR 字符串:

str
要截断的 C 字符串。请注意,此字符串由 被分解成更小的字符串(令牌)。或者,一个空 可以指定指针,在这种情况下函数继续 扫描上一次成功调用函数的位置。

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

此外,它不应该是一个常量字符串(例如char* myStr = "constant string";).参见here

它可以在本地分配,也可以通过 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);
}

注意:本示例展示了如何遍历字符串...由于原始字符串已损坏,strtok(...) 会记住您上次所在的位置并继续处理字符串。

【讨论】:

    【解决方案3】:

    根据docs

    返回值

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2010-09-08
      • 2012-01-22
      • 2013-07-31
      • 1970-01-01
      相关资源
      最近更新 更多