2012-10-03 54 views
0

我有Valgrind的報告錯誤:初始化變量將爲pid_t

==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; 

但這仍然導致相同的錯誤。這段代碼在這個過程中被多次調用。

回答

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 ------------------^ 
} 
+0

謝謝,是的,這些是兩個不同的變量。 – user1681210