Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valgrind C++ memory leaks

Tags:

c++

valgrind

I have this demonstrable piece of code:

#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;
}

This is causing in Valgrind an error, but I really don't know what does that mean and how to fix it... could anyone give me an advice?

==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)
like image 995
Radek Simko Avatar asked Nov 21 '10 21:11

Radek Simko


1 Answers

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

You are passing matrix[0] as a parameter without initializing it beforehand.

like image 160
Šimon Tóth Avatar answered Sep 20 '22 22:09

Šimon Tóth