代码之家  ›  专栏  ›  技术社区  ›  Radek Simko

Valgn+C++内存泄漏

  •  6
  • Radek Simko  · 技术社区  · 14 年前

    我有一段明显的代码:

    #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)
    
    3 回复  |  直到 13 年前
        1
  •  6
  •   Å imon Tóth    14 年前

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

    matrix[0]

        2
  •  2
  •   John Smith    13 年前

        3
  •  2
  •   Richard J. Ross III    13 年前