0

Valgrind 报告了一个错误:

==5644== Conditional jump or move depends on uninitialised value(s)

这发生在类型变量上pid_t

我的代码如下:

GmpPipePlayer::GmpPipePlayer( IOBase *pIO, Referee *pBack, PieceColor pc, int size, const DataBoard *pBd, int handicap, const char *cmd_line, int bDebug )
    : GmpPlayer(pIO, pBack, pc, size, pBd, handicap, bDebug)
{
    int down[2], up[2];
        pid_t _pid;  //here the var is declared

    pipe(down);   
    pipe(up);


    _pid = fork();

    if (_pid < 0)
        exit(1);


    if (_pid == 0)
    {
        close(down[1]);
        close(up[0]);

        dup2(down[0], 0);
        dup2(up[1], 1);

        execl("/bin/sh", "sh", "-c", cmd_line, NULL);

        _exit(1);
    }

    close(down[0]);
    close(up[1]);
    _down = down[1];
    _up = up[0];

    _reader_thd = new Thread(reader_wrapper, this);
}

GmpPipePlayer::~GmpPipePlayer()
{
    if (_pid > 0)   //valgrind is reporting that the error is here!!
    {
        kill(_pid, SIGTERM);
        _pid = 0;
    }

    if (_up)
    {
        close(_up);
        _up = 0;
    }

    if (_down)
    {
        close(_down);
        _down = 0;
    }   
       delete _reader_thd
}

所以,我认为问题是_pid没有初始化,应该如何初始化这个变量?我试过这样:

 pid_t _pid=0;

但这仍然导致同样的错误。这段代码在此过程中被多次调用。

4

1 回答 1

2

看来您有两个变量被调用_pid- 您在构造函数中声明的本地变量:

pid_t _pid;  //here the var is declared

以及您在析构函数中访问的那个:

if (_pid > 0)   //valgrind is reporting that the error is here!!

这些变量并不相同:您在析构函数中访问的变量必须是全局变量或实例变量(更有可能)。

由于您依赖于_pid将状态从构造函数传递给析构函数,因此您需要从构造函数中删除本地声明,并根据需要初始化其他声明_pid。如果它是一个实例变量,则将其初始化添加到初始化器列表中,如下所示:

GmpPipePlayer::GmpPipePlayer( IOBase *pIO, Referee *pBack, PieceColor pc, int size, const DataBoard *pBd, int handicap, const char *cmd_line, int bDebug )
: GmpPlayer(pIO, pBack, pc, size, pBd, handicap, bDebug), _pid(0) {
    ... //                         HERE ------------------^
}
于 2012-10-03T01:03:02.507 回答