Gil*_*een -1 c malloc valgrind
代码如下:
Board* constructBoard(int dimension)
{
//Allocate memory for board
Board *board = malloc(sizeof(Board));
if(!board)
{
return NULL;
}
//Allocate memory for matrix
board->matrix = malloc(dimension * sizeof(int*));
if(!board->matrix)
{
freeBoard(board);
return NULL;
}
//Allocate memory for each row of matrix
for(int row = 0; row < dimension; row++)
{
// Following line is line 29 from error below <---------------------------
board->matrix[row] = malloc(dimension * sizeof(int));
if(!board->matrix[row])
{
freeBoard(board);
return NULL;
}
board->dimension = row +1;
}
board->value = 0;
return board;
}
void printBoard(Board *board, char* delimiter)
{
assert(board && "printBoard must get an initialized board");
for(int i = 0; i < board->dimension; i++)
{
for (int j = 0; j < board->dimension; j++)
{
printf("%d%s", board->matrix[i][j], delimiter);
}
printf("\n");
}
}
Run Code Online (Sandbox Code Playgroud)
当从main调用这样的时候:
Board *final = constructBoard(4);
printBoard(final, SEPARATOR);
freeBoard(final);
Run Code Online (Sandbox Code Playgroud)
导致以下valgrind错误(请参阅上面代码中的注释错误行):
==8450== Uninitialised value was created by a heap allocation
==8450== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8450== by 0x401560: constructBoard (Board.c:29)
==8450== by 0x400FAB: main (SudokuSolver.c:181)
Run Code Online (Sandbox Code Playgroud)
定义Board:
typedef struct Board
{
int** matrix;
int dimension;
unsigned int value;
} Board;
Run Code Online (Sandbox Code Playgroud)
当我不添加呼叫printBoard一切都很好.
printBoard?constructBoard?我已经读过这些先前的问题,但我仍然无法解决它,因为我正确分配了内存并确保循环仅迭代有效索引:
我用以下标志编译:
gcc -g -c -Wextra -Wall -Wvla -DNDEBUG -std=c99
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2011 次 |
| 最近记录: |