0

I'm in the process of making a program that parses words from a line, adding a word to a tree when it hits an nonalphanumeric character. Everything goes fine when there are no spaces in a line. However, when there are nonalphanumeric characters, the loop in question (beginning at the line commented in the code) halves in size!

Why does the loop halve?

Tree addin (char* filee, Tree tree)
{
    int i;
    FILE *fp;
    fp = fopen(filee, "r");
    char* hold2 = malloc(99);
    int count=-1;
    char* hold;
    while ((hold=getLine(fp))!=NULL)
    {
        count=-1;
        for (i=0; i<strlen(hold); i++) //The loop in question
        {
            count++;
            if ((isalnum(hold[count])==0)&&(hold[count]!='\n'))
            {
                strncpy(hold2, hold, count);
                hold2[count]='\0';
                hold=strdup(&hold[count+1]);
                count=-1;
                tree = insertT(tree, hold2);
            }
        }
        tree = insertT(tree, hold);
    }
    free(hold);
    fclose(fp);
    return tree;
}
4

2 回答 2

5

当您找到一个非字母数字字符时,您的程序会移动hold以指向字符串的其余部分,但不会重置i。这意味着您继续从新指针开始迭代,新hold指针是原始指针的一部分,再加i上当时发生的任何事情。这样做可能至少会跳过一堆字符,并且可能会让您开始在字符串之外的内存上进行操作,这绝对是个坏消息。

于 2013-05-06T04:24:02.950 回答
0

这可能是因为您hold在循环内更改了 的值,因为strlen(hold)在每次迭代时都会重新评估。一种解决方案可能是strlen(hold)在进入for循环之前保存 的值。

于 2013-05-06T04:25:43.567 回答