strtok和自由

时间:2013-04-12 16:28:24

标签: c free strtok

这样做有什么问题:

void *educator_func(void *param) {
char *lineE = (char *) malloc (1024);
size_t lenE = 1024;
ssize_t readE;

FILE * fpE;

fpE = fopen(file, "r");

if (fpE == NULL) {
    printf("ERROR: couldnt open file\n");
    exit(0);
}

while ((readE = getline(&lineE, &lenE, fpE)) != -1) {
    char *pch2E = (char *) malloc (50);

    pch2E = strtok(lineE, " ");

    free(pch2E);
}

free(lineE);
fclose(fpE);

return NULL;
}

如果我删除行'pch2E = strtok(lineE, " ");',它可以正常工作......

为什么我不能在那里做strtok()?我尝试了strtok_r()也没有运气,它给了我无效的免费(地址0x422af10是一个大小为1,024的块内的0字节免费)

2 个答案:

答案 0 :(得分:2)

您的代码未执行您认为正在执行的操作...对pch2E = strtok(lineE, " ");的调用正在将pch2E的值替换为strtok的返回值lineE lineE 1}}或新分配的int firstPass = 1; while ((readE = getline(&lineE, &lenE, fpE)) != -1) { char* pch2E = strtok( firstPass ? lineE : NULL, " "); firstPass = 0; } free(lineE);

替代品

您可以按照以下方式修复...

while ((readE = getline(&lineE, &lenE, fpE)) != -1) 
{
    char* pch2E;
    int firstPass = 1;

    while( (pch2E = strtok( firstPass ? lineE : NULL, " ")) != NULL )
    {
        firstPass = 0;
        // do something with the pch2E return value
    }
}

free(lineE);

我应该补充一点,我看你的代码越多,它对我来说就越有根本性的缺陷。您需要在代码中使用内部循环来处理标记,而外部循环正在加载行...

{{1}}

答案 1 :(得分:1)

strtok返回一个指向令牌的指针,该指针包含在你传递的字符串中,所以你不能释放它,因为它不会(总是)指向你用malloc分配的东西。

这种赋值甚至不能在C中工​​作,如果你想要一个将令牌复制到缓冲区的函数,它会是这样的:

tokenize(char* string, char* delimiter, char* token);

你需要传递一个有效的指针指向令牌,用于复制数据的函数。在C中复制指针中的数据,该函数需要访问该指针,因此函数不可能在返回值上做。

另一种策略(但最差)将是一个在内部分配内存并返回指向需要被调用者释放的内存区域的指针的函数。

对于你的问题,需要多次调用strtok来返回所有标记,直到它返回null,所以它应该是:

while ((readE = getline(&lineE, &lenE, fpE)) != -1) {
    char *pch2E;

    pch2E = strtok(lineE, " "); //1st token

    while ((pch2E = strtok(NULL, " ")) != NULL) {
        //Do something with the token
    }
}