Reputation: 37299
The code below:
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");
}
}
When called from main like this:
Board *final = constructBoard(4);
printBoard(final, SEPARATOR);
freeBoard(final);
Results in the following valgrind error (See comment in code above for line of error):
==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)
Definition of Board
:
typedef struct Board
{
int** matrix;
int dimension;
unsigned int value;
} Board;
When I do not add the call to printBoard
everything is fine.
printBoard
?constructBoard
?I've read these previous questions but I still didn't manage to solve it as I properly allocated the memory and made sure loops iterate only valid indexes:
I've compiled with the following flags:
gcc -g -c -Wextra -Wall -Wvla -DNDEBUG -std=c99
Upvotes: 0
Views: 6789
Reputation: 409196
The malloc
function only allocates memory, it does not initialize that memory in any way. The contents of the memory is indeterminate.
You print the contents of this uninitialized memory in the printBoard
function, leading to the warning you get.
If you want to initialize the memory, then either do it explicitly or use calloc
to allocate and "clear" (zero) the memory (it's equivalent to malloc
followed by memset
).
Upvotes: 12