开发者

C++ Beginner - Simple block of code crashing, reason unknown

Here's a block of code I'm having trouble with.

string Game::tradeRandomPieces(Player & player)
{
  string hand = player.getHand();
  string piecesRemoved;
  size_t index;
  //Program crashes while calculating numberOfPiecesToTrade...
  size_t开发者_StackOverflow中文版 numberOfPiecesToTrade = rand() % hand.size() + 1
  for (; numberOfPiecesToTrade != 0; --numberOfPiecesToTrade)
  {
    index = rand() % hand.size();
    piecesRemoved += hand[index];
    hand.erase(index,1);
  }

  player.removePiecesFromHand(piecesRemoved);
  player.fillHand(_deck);

  return piecesRemoved;
}

I believe the code is pretty self explanatory.

fillhand and removepiecesfromhand are working fine, so that's not it. I really can't get what's wrong with this :(

Thanks for your time

EDIT OK, I found out where the program crashes. Added a comment to the above source code.


If the hand is empty, then this operation:

rand() % hand.size() 

In the initializer of the for loop, will be attempting to perform a modulus by 0, which is essentially division by zero. That is your crash.

Add a test to make sure the hand is not empty before proceeding with the rest of the method.


stick a breakpoint into your for loop to give you a better idea of what's going on. I would bet that the for loop is going infinite and causing the program to hang.

On hitting the breakpoint, check your iterator variables and see if you can see anything out of the ordinary


Maybe you want to use

 for (size_t numberOfPiecesToTrade = rand() % hand.size() + 1; numberOfPiecesToTrade > 0; --numberOfPiecesToTrade)

to make things clearer.

Edit: If you run in debug mode, than wo don't you just debug? :) This "not responding" message is afaik often caused by an infinite loop.

Edit2: I don't know if i am correct, but could it be that in some cases you will miss the numberOfPiecesToTrade != 0 condition if the initialvalue of numberOfPiecesToTrade is 1? I'm not familiar with size_t though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜