Gilad Green
Gilad Green

Reputation: 37299

Uninitialised value was created by a heap allocation when calling different function

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.

  1. Why do I get the error only when I use printBoard?
  2. Why when I get the error it says it is in the 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:

  1. Uninitialised value was created by a stack allocation
  2. Uninitialised value was created by a stack allocation - valgrind
  3. Uninitialised value was created by a stack allocation

I've compiled with the following flags:

gcc -g -c -Wextra -Wall -Wvla -DNDEBUG -std=c99

Upvotes: 0

Views: 6789

Answers (1)

Some programmer dude
Some programmer dude

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

Related Questions