0

I want to write a function which removes certain word from text file. Program works fine but valgrind says something different:

==3411== Source and destination overlap in strcpy(0x51f1c90, 0x51f1c92)
==3411==    at 0x4C2C085: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3411==    by 0x400AD7: DELTEword (remove2.c:113)
==3411==    by 0x4009A1: main (remove2.c:73)

also when I am trying to remove for instance word: "go" sometimes it happens that word "ro" is also removed. Why?

Here's my code:

int DELTEword(char *word, char *KEYword)
{
    int i, k = 0, l = 0, length;
    char *ptr;

    if(word != NULL)
    {
        length = strlen(KEYword);
        for(i = 0; word[i] != '\0'; i++)
        {
            if(word[i] == KEYword[k])
            {
                l++;
                k++;
            }

            if(l == length)
            {
                ptr = &word[i];
                strcpy((ptr - length) + 1, ptr + 1);
                l = 0;
                k = 0;
            }
        }
        return 1;
    }
    else return 0;
 }
4

2 回答 2

3

如果源和目标重叠,则不建议使用memmove而不是对strcpy数据进行混洗。在重叠情况下使用是安全的..strcpymemmove

于 2013-09-13T10:14:16.363 回答
0

我认为问题在于以下代码

for(i = 0; word[i] != '\0'; i++)
{
    if(word[i] == KEYword[k])
    {
        l++;
        k++;
    }
}

它不寻找连续的字母。如果字母不匹配,则从下一个继续。我的意思else是缺少零件处理。

可能这有帮助。这匹配所有出现,我的意思gogood. 可以根据您的需要进行调整。

length = strlen(KEYword);
for(i = 0; word[i] != '\0'; i++)
{
    k = i;
    l = 0;
    for (j = 0; j < length; j++) {
        if(word[k] == KEYword[j])
        {
            l++;
            k++;
        }
        else
        {
            break;
        }
    }
    /* All letters matched */
    if (l == length) {
        /* do some stuff */
    }
}
于 2013-09-13T10:28:34.127 回答