调用不同函数

时间:2017-08-29 07:50:25

标签: 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");
    }
}

从主要电话中调用时:

Board *final = constructBoard(4);
printBoard(final, SEPARATOR);
freeBoard(final);

导致以下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)

Board的定义:

typedef struct Board
{
    int** matrix;
    int dimension;
    unsigned int value;
} Board;

当我不将呼叫添加到printBoard时,一切都很好。

  1. 为什么我只在使用printBoard时才会收到错误?
  2. 为什么当我收到错误信息表明它出现在constructBoard
  3. 我已经阅读过这些以前的问题,但我仍然没有设法解决它,因为我正确分配了内存并确保循环只迭代有效索引:

    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
    4. 我使用以下标志编译:

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

1 个答案:

答案 0 :(得分:11)

malloc函数只分配内存,它不会以任何方式初始化该内存。内存的内容是不确定

您在printBoard功能中打印此未初始化内存的内容,从而产生警告。

如果你想初始化内存,那么要么明确地做,要么使用calloc来分配和“清除”(零)内存(相当于malloc后跟memset )。