6
0x004069f1 in Space::setPosition (this=0x77733cee, x=-65, y=-49) at space.h:44    
0x00402679 in Checkers::make_move (this=0x28cbb8, move=...) at checkers.cc:351
0x00403fd2 in main_savitch_14::game::make_computer_move (this=0x28cbb8) at game.cc:153
0x00403b70 in main_savitch_14::game::play (this=0x28cbb8) at game.cc:33
0x004015fb in _fu0___ZSt4cout () at checkers.cc:96
0x004042a7 in main () at main.cc:34

こんにちは、私はクラスのゲームをコーディングしていて、segfault に遭遇しています。チェッカー ピースは 2 次元配列に保持されるため、問題のビットは配列に対して無効な x/y のように見えます。移動は文字列として渡され、整数に変換されるため、x と y はなぜか ASCII NULL でした。関数呼び出し make_move で move=... と表示されていることに気付きました。

move=... と表示されるのはなぜですか? また、セグメンテーション違反を解決するための他の簡単なヒントはありますか? 私はGDBの初心者です。

4

2 に答える 2

8

Basically, the backtrace is trace of the calls that lead to the crash. In this case:

game::play called game::make_computer_move which called Checkers::make_move which called Space::setPosition which crashed in line 44 in file space.h.

Taking a look at this backtrace, it looks like you passed -65 and -49 to Space::setPosition, which if they happen to be invalid coordinates (sure look suspicious to me being negative and all). Then you should look in the calling functions to see why they have the values that they do and correct them.

I would suggest using assert liberally in the code to enforce contracts, pretty much any time you can say "this parameter or variable should only have values which meet certain criteria", then you should assert that it is the case.

A common example is if I have a function which takes a pointer (or more likely smart pointer) which is not allowed to be NULL. I'll have the first line of the function assert(p);. If a NULL pointer is ever passed, I know right away and can investigate.

Finally, run the application in gdb, when it crashes. Type up to inspect the calling stack frame and see what the variables looked like: (you can usually write things like print x in the console). likewise, down will move down the call stack if you need to as well.

As for SEGFAULT, I would recommend runnning the application in valgrind. If you compile with debugging information -g, then it often can tell you the line of code that is causing the error (and can even catch errors that for unfortunate reasons don't crash right away).

于 2012-06-02T03:11:55.413 に答える