我有根据输入动态分配的矩阵。一行输入是矩阵中的一行。分配以 EOF 结束。问题是,如果我输入多于一行,valgrind 会显示这一点。 我真的不知道出了什么问题。
==6142== Conditional jump or move depends on uninitialised value(s)
==6142== at 0x402C5F9: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==6142== by 0x80488F4: reallocMe (in /home/jan/NetBeansProjects/PA1/pokus)
==6142== by 0x80493CC: readMatrix (in /home/jan/NetBeansProjects/PA1/pokus)
==6142== by 0x804962A: main (in /home/jan/NetBeansProjects/PA1/pokus)
==6142== Uninitialised value was created by a heap allocation
==6142== at 0x402C63E: realloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==6142== by 0x80488A4: reallocMe (in /home/jan/NetBeansProjects/PA1/pokus)
==6142== by 0x80493CC: readMatrix (in /home/jan/NetBeansProjects/PA1/pokus)
==6142== by 0x804962A: main (in /home/jan/NetBeansProjects/PA1/pokus)
有reallocMe()函数
int ** reallocMe(int ** resultsMatrix, int rows, int cols) {
int i;
resultsMatrix = (int **) realloc(resultsMatrix, sizeof(*resultsMatrix)*rows);
if(!resultsMatrix)
return NULL;
for(i = 0; i < rows; i++) {
resultsMatrix[i] = (int *) realloc(resultsMatrix[i], sizeof(*resultsMatrix[i])*cols);
if(!resultsMatrix[i]) {
freeMatrix(resultsMatrix, i);
return NULL;
}
}
return resultsMatrix;
}
还有 readMatrix() 函数,我在其中调用 reallocMe()
int ** readMatrix(int ** matrix, int * rows, int * cols, int * matrixSum) {
int number;
char delimiter;
int numbersCount = 0;
int delimitersCount = 0;
int breaker = 0;
int actualCol = 0;
int ** test;
printf("Enter the matrix:\n");
while (1) {
if (scanf("%d", &number) != 1) break;
numbersCount++;
if(number <= 0) breaker = 1;
if (*rows == 1)
*cols = *cols +1;
/* Memory allocation */
test = reallocMe(matrix, *rows, *cols);
if(!test) {
freeMatrix(matrix, *rows);
return NULL;
}
matrix = test;
matrix[*rows-1][actualCol] = number;
*matrixSum += number;
actualCol++;
if (scanf("%c", &delimiter) == 1 && delimiter == ',') {
delimitersCount++;
} else if(iscntrl(delimiter)) {
if ((actualCol > *cols) && (*rows > 1)) { /* if the count of columns is not same on every row, then break */
freeMatrix(matrix, *rows);
return NULL;
}
if((*rows * *cols)-*rows != delimitersCount) {
freeMatrix(matrix, *rows);
return NULL;
}
actualCol = 0;
*rows = *rows + 1;
} else {
freeMatrix(matrix, *rows);
return NULL;
}
}
*rows = *rows - 1;
if (!feof(stdin)) {
freeMatrix(matrix, *rows);
return NULL;
}
if(*rows * *cols != numbersCount) {
freeMatrix(matrix, *rows);
return NULL;
}
if(breaker == 1) {
freeMatrix(matrix, *rows);
return NULL;
}
if(*rows * *cols == 1) {
freeMatrix(matrix, *rows);
return NULL;
}
return matrix;
}
我不知道如何解决这个问题。谁能给我一些建议、提示等等?谢谢:)
最佳答案
realloc
不会将新内存清零。因此,为每行分配内存的循环对于新行来说是不正确的。
要解决此问题,您应该在循环之前将指向新(添加)行的所有指针归零,或者仅对旧行运行 realloc
循环,并使用 malloc
对于新的。
关于C - 矩阵重新分配和未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20109986/