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开发者_StackOverflow[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)
matrix[0] = (int *) realloc(matrix[0], c * sizeof (int));
You are passing matrix[0]
as a parameter without initializing it beforehand.
You can use more powerfull utility. BoundsChecker, Deleaker, XWatcher...
I advise you to use deleaker - a powerful tool for debugging memory leaks!
精彩评论