可能的堆损坏,使用valgrind进行调试

时间:2014-07-29 05:48:37

标签: c string valgrind heap-memory heap-corruption

我正在开发一个使用字符串缓冲区的项目。我使用free()和malloc()得到随机错误 - 喜欢"无效的下一个尺寸(快)"并怀疑是否是由于某些内存堆损坏。我正在使用gcc。我在二进制文件中使用了valgrind,这是摘要:

ERROR SUMMARY: 26887 errors from 39 contexts (suppressed: 0 from 0)

我认为这有点太高了。我附加了valgrind memcheck输出here的pastebin 大多数问题似乎来自单个函数:strbuf_addc()。 strbuf是一个可以自动增长的字符串缓冲区。我在这里粘贴了一些strbuf函数。

int strbuf_add(struct strbuf *string, const char *c)
{
    if(string == NULL || c == NULL) return 0;

    while(*c != '\0') {
        if(!strbuf_addc(string, *c++))
            return 0;
    }

    return 1;
}

 int strbuf_addc(struct strbuf *string, char c)
    {
        size_t space_available;

        assert(string != NULL);

        space_available = string->allocated - string->length;
        if(space_available <= 1) {
            if(!grow_buffer(string)) {
                return 0;
            }
        }
        string->buffer[string->length++] = c;
        string->buffer[string->length] = '\0';

        return 1;
    }
    static int grow_buffer(struct strbuf *string)
{
    char *tmp;
    size_t toallocate;

    assert(string != NULL);

    toallocate = string->allocated + (string->allocated / 2);
    tmp = (char*) realloc(string->buffer, toallocate);
    if(tmp) {
        string->buffer = tmp;
        string->allocated = toallocate;
        return 1;
    }
    return 0;
}

我不确定strbuf_addc是否是我写的罪魁祸首或其他一些功能。请看一下。我基本上将字符串文字作为strbuf_add的第二个参数传递。我不确定它们是否会被终止,但我认为c中的字符串文字是空终止的。我也试过从文件中读取字符串,但仍有一些错误。

1 个答案:

答案 0 :(得分:3)

toallocate = string->allocated + (string->allocated / 2);

可能会出现toallocate不会大于string->allocated的情况。因此,realloc不会为您的字符串保留更多空间,您将无法添加字符。 valgrind一直说:

==4755== Invalid write of size 1

所以你没有空间来附加一个字符。

相关问题