valgrind - 地址是分配大小为 16 的块之前的 2 个字节

valgrind - Address is 2 bytes before a block of size 16 alloc'd

我在尝试理解为什么 valgrind 告诉我我在 char * 数组中越界时遇到了一些问题。

每当我尝试从 nul 字节之前开始向后迭代数组时。它抛出错误,我正在访问我不应该访问的内存。

这是我的第一个函数:

char *ReadLineFile(FILE *infile) {
    int initSize = 16;
    char *string = NULL;
    string = malloc(sizeof(char) * initSize);
    if(string == NULL){
        exit(-1);
    }

    char val;
    int valSize = 0;
    while((val = fgetc(infile)) != EOF){
        if(val == '\n'){
            break;
        }

        if(valSize == initSize){
            initSize *= 2;
            string = realloc(string, initSize * sizeof(char));
        }

        string[valSize++] = val;
    }

    if(valSize == initSize){
        initSize++;
        string = realloc(string, initSize * sizeof(char));
    }

    string[valSize++] = '[=10=]';

    return trimString(string);
}

这是我的第二个功能:

char *trimString(char *string) {
    int start = 0;
    int end = strlen(string);

    while(string[start] == ' '){start++;}
    while(string[end-2] == ' '){end--;}  // the [end-2] causes the error in valgrind

    int trimLen = end - start;
    char *trimmedStr = malloc(sizeof(char) * (trimLen + 1));
    if(trimmedStr == NULL){
        exit(-1);
    }

    int i = 0;
    while(start != end){
        trimmedStr[i] = string[start];
        i++; start++;
    }

    trimmedStr[i] = '[=11=]';
    free(string);

    return trimmedStr;
}

Valgrind 错误:

==3809== Invalid read of size 1
==3809==    at 0x1090D5: trimString (myio.c:129)               
==3809==    by 0x109080: ReadLineFile(myio.c:120)
==3809==    by 0x108C54: main (driver2.c:29)
==3809==  Address 0x522e03e is 2 bytes before a block of size 16 alloc'd
==3809==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload/memcheck-amd64-linux.so)
==3809==    by 0x108F91: ReadLineFile(myio.c:90)
==3809==    by 0x108C54: main (driver2.c:29)

我希望 valgrind 不会出现错误,因为我在字符串中分配了足够的内存,但它告诉我我正在尝试访问内存,而当我尝试向后迭代数组时,我不应该访问这些内存。我想了解是什么原因造成的,因为我花了多个小时试图找出这个错误。谢谢!

如果该行只是空格或空行怎么办?

在那种情况下 while(string[end-2] == ' '){end--;} 可能会到达线路的开头并继续行走 "backwards"。

考虑测试行/字符串的限制。另外,为什么 -2?为什么不 -1?即:

while(end > start && string[end - 1] == ' ') --end;

这种方法可以保护您免受 "walking" 太远的影响。

旁注:

EOF 标记不是有效字节(它不在 0-255 值范围内)。如果是,它可能是文件中间的有效值。

因此,char 中不能包含 EOF 您无法测试 char 是否包含 EOF。使用 int val 而不是 char val.