条件跳转或移动取决于未初始化的值

时间:2011-08-17 08:34:34

标签: c valgrind

我现在一直在努力解决这个问题,搜索每一个可能的解决方案。我是C的新手,所以我很难。我知道我有一些未初始化的变量,但我找不到它们。我正在尝试打印矩阵。这是构造函数:

BoardP createNewBoard(int width, int high)
{  

    BoardP board = (BoardP) malloc(sizeof(Board));

    if (board == NULL)
    {
        reportError(MEM_OUT);
        return NULL;
    }
    board->height = high;
    board->width = width;
    board->board = (char**) malloc(high * sizeof(char*));
    int i;
    for (i=0; i<high; i++)
    {
        board->board[i] = (char*) malloc(width * sizeof(char));
        if (board->board[i] == NULL)
        {
            freeTempBoard(board,i);
            return NULL;
        }
    }

    return board;
}

构造函数返回BoardP,这是对Board的一个pinter,它是:

typedef struct Board
{
    int width;
    int height;
    char **board;
} Board;

现在我没有尝试打印电路板 - >板。我循环遍历矩阵,对于每个单元格,我称之为函数:

static void printChar(ConstBoardP board, int X, int Y)
{
    if (X>=board->height || Y>=board->width)
    {
        printf(" ");
    }
    else
    {
        printf("%c ",board->board[X][Y]); //!!THIS IS LINE 299 IN Board.c!!
    }
}

而且这是我得到的错误:

==4931== Conditional jump or move depends on uninitialised value(s)
==4931==    at 0x4E973D9: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:880)
==4931==    by 0x4E6F01B: vfprintf (vfprintf.c:1614)
==4931==    by 0x4E75879: printf (printf.c:35)
==4931==    by 0x400D91: printChar (Board.c:299)
==4931==    by 0x400CED: printBoard (Board.c:284)
==4931==    by 0x400F1A: main (PlayBoard.c:19)
==4931== 
==4931== Conditional jump or move depends on uninitialised value(s)
==4931==    at 0x4E97401: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:887)
==4931==    by 0x4E6F01B: vfprintf (vfprintf.c:1614)
==4931==    by 0x4E75879: printf (printf.c:35)
==4931==    by 0x400D91: printChar (Board.c:299)
==4931==    by 0x400CED: printBoard (Board.c:284)
==4931==    by 0x400F1A: main (PlayBoard.c:19)
==4931== 
==4931== Conditional jump or move depends on uninitialised value(s)
==4931==    at 0x4E6F025: vfprintf (vfprintf.c:1614)
==4931==    by 0x4E75879: printf (printf.c:35)
==4931==    by 0x400D91: printChar (Board.c:299)
==4931==    by 0x400CED: printBoard (Board.c:284)
==4931==    by 0x400F1A: main (PlayBoard.c:19)

现在有另一个文件调用createNewBoard,然后创建printBoard(newBoard,0,0)。唯一可能未被初始化的是董事会和董事会,除此之外,我没有任何想法。我不知道如何调试它。 我知道很多文字,但我找不到问题。任何想法都会非常感激

3 个答案:

答案 0 :(得分:5)

尝试:

for (i=0; i<high; i++)
{
    board->board[i] = (char*) malloc(width * sizeof(char));
    /* ... */
    memset(board[i], 0, width);
}

答案 1 :(得分:3)

malloc没有初始化内存,所以:

printf("%c ",board->board[X][Y]);

可能未初始化。请改为使用calloc或在

之后添加memset
board->board[i] = (char*) malloc(width * sizeof(char));

答案 2 :(得分:0)

在这一行:

board->board[i] = (char*) malloc(width * sizeof(char));

...你为电路板行分配空间,但你从来没有真正初始化这个数组中的值。使用memset(board[i], 0, width)或显式循环数组以设置值。

(另外,作为一种风格,你不需要cast malloc's return value。)