Tôi có mảnh thể chứng minh mã này:Valgrind C++ rò rỉ bộ nhớ
#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;
}
Điều này gây ra trong Valgrind một lỗi, nhưng tôi thực sự không biết điều gì đó có nghĩa là và làm thế nào để sửa chữa nó ... có thể bất cứ ai cho tôi một lời khuyên?
==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)
Bạn chưa khởi tạo ma trận [0] trước cuộc gọi realloc thứ hai của mình. Nó có thể được lấp đầy với bất cứ thứ gì. – wj32
BTW, hãy xem xét sử dụng các container STL, 'std :: vector' là sự lựa chọn hợp lý nhất. Không có realloc, không có rắc rối. –
Dialecticus
Nếu nó là mảng 2 chiều, với giá trị nào cần được điền vào? –