c - 调用不同函数时,堆分配创建了未初始化的值

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

当像这样从 main 调用时:

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)

董事会的定义:

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

当我不添加对 printBoard 的调用时,一切都很好。

  1. 为什么只有在使用 printBoard 时才会出现错误?
  2. 为什么当我收到错误时,它说它在 constructBoard 中?

我已经阅读了前面的这些问题,但我仍然无法解决它,因为我正确分配了内存并确保循环仅迭代有效的索引:

  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

我使用以下标志进行编译:

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

最佳答案

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

您在 printBoard 函数中打印此未初始化内存的内容,从而导致收到警告。

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

关于c - 调用不同函数时,堆分配创建了未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45933532/

相关文章:

c - Strace 与 C 可执行文件?

c++ - 如果我在 C++ 中为类型为 "std::string &"的参数指定默认值,会导致内存泄漏吗?

c - 使用 valgrind 循环中的 malloc

c - 在C中将字符串设置为空字符串

字符串操作中的 C 段错误

c - gettimeofday 差异没有给我时间范围

c - Sqlite3 - 试图在回调中填充结构

c - malloc 不存在的物理地址错误

c++ - Callgrind 内联函数

java - 将 native (C) 指针保存到对象实例中——然后清理它