c++ - Valgrind C++ 内存泄漏

标签 c++ valgrind

我有这段可演示的代码:

#include <cstdlib>
#include <cstdio>

int main() {
    int ** matrix = NULL;
    int c = 1, input = 0;

    printf("Enter first row of the matrix:\n");
    while (!feof(stdin)) {
        input = fgetc(stdin);

        matrix = (int**) realloc(matrix, 1 * sizeof (int*));
        if (matrix == NULL) {
            printf("Troubles with memory allocation!\n");
            return 0;
        }
        matrix[0] = (int *) realloc(matrix[0], c * sizeof (int));
        matrix[0][c-1] = (int) input;

        c++;
    }

    free(matrix[0]);
    free(matrix);

    return 0;
}

这会在 Valgrind 中导致错误,但我真的不知道那是什么意思以及如何解决它...有人可以给我建议吗?

==30031== 1 errors in context 1 of 1:
==30031== Conditional jump or move depends on uninitialised value(s)
==30031==    at 0x402868B: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30031==    by 0x80485CB: main (main.cpp:17)
==30031==  Uninitialised value was created by a heap allocation
==30031==    at 0x402860A: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30031==    by 0x4028694: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30031==    by 0x80485A6: main (main.cpp:12)

最佳答案

matrix[0] = (int *) realloc(matrix[0], c * sizeof (int));

您正在将 matrix[0] 作为参数传递,而没有事先对其进行初始化。

关于c++ - Valgrind C++ 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4240431/

相关文章:

c++ - 将对象传递给函数时,必须重载哪些运算符才能查看所有操作?

daemon - valgrind 是否适用于 Daemon 程序

c++ - 大小为 4 的迭代器无效读取

c - 即使在调用 fclose() 之后,由于 fopen() 而导致的内存泄漏

c++ - 错误:无法开始调试。命令 “-exec-run”的意外GDB输出。找不到进程ID 1401的Mach任务端口

c++ - RBM 在代码上与 OpenACC 没有改进

c++ - 优化与未优化构建的 KCachegrind 输出

c++ - 我应该担心 "Conditional jump or move depends on uninitialised value(s)"吗?

c++ - Boost.Test 检查指针是否为空

c++ - 将 RGB 编码为 H.264