Valgrind "Invalide write of size 1"

Valgrind "Invalide write of size 1"

下面我写了一个函数_getstr(),不使用scanf来获取输入中的字符串。 运行 valgrind,然而,结果 "Invalid write of size 1" 错误。每个输入都会发生这种情况。是什么导致了这个错误?

char *_getstr(){
    char *str = NULL;
    int bufsize = 0, c = 0;
    do {
        c = getchar();
        if (c != '\n'){
            str = realloc(str, (bufsize + 1)*sizeof(char));
            str[bufsize++] = c;
        }
    } while (c != '\n');
    str[bufsize] = '[=11=]';
    return str;
}

主要是我这样做:

char *s1 = _getstr();

当我插入输入时,valgrind 的输出是这样的:

Insert of the first string: hello
==6830== Invalid write of size 1
==6830==    at 0x109294: _getstr (changeJOIN.c:43)
==6830==    by 0x10919B: main (changeJOIN.c:15)
==6830==  Address 0x4a419b4 is 0 bytes after a block of size 4 alloc'd
==6830==    at 0x4839D7B: realloc (vg_replace_malloc.c:826)
==6830==    by 0x109264: _getstr (changeJOIN.c:39)
==6830==    by 0x10919B: main (changeJOIN.c:15)

当您添加终止空字节时,str 指向 bufsize 字节,因此 str[bufsize] = '[=13=]'; 在分配的内存末尾后写入一个元素。这就是它抱怨的 valgrind。

您需要在添加空终止符之前再分配一个字节。

str = realloc(str, (bufsize + 1)*sizeof(char));
str[bufsize] = '[=10=]';