Search code examples
c++structlinked-listqueuedynamic-memory-allocation

How do I declare a dynamic array of structs that contain a Queue member?


This is from a homework assignment that was already turned in. The program is a card game that plays correctly but seg faults when the game is over. I can trace the core dump to my delete [] playerArr, but I think the real problem is in how I'm declaring my playerArr.

I have a constructor, copy, overloaded operator and destructor in my .h file that works well with other programs so I think my problem is in main. I've looked at several other questions here and on google and haven't found one quite like this. Here are the code snippets:

struct Player
{
  int currentHand;    //current number of cards in given player's hand
  Queue hand;         //queue to store player's hand
};

in main I allocate an array of structs, I think this is my problem. I've trial and errored a variety of approaches but this one allows my program to compile and my game to play as designed:

    //allocate array of Player structs
    Player *playerArr = new Player[numPlayers];
    for (int i = 1; i <= numPlayers; i++)
      playerArr[i].currentHand = 0;
    //enqueue playerArr.hand
    deal(playerArr, deck, numPlayers, currentDeck);

this is the sequence I use to clean up before deleting, the core dumps after cout:

   //exit do-while loop and end game
            }
  while (playerArr[currentPlayer - 1].currentHand != 0);


  for (int i = 1; i < numPlayers; i++)
    {
      while (playerArr[i].currentHand > 0)
        {
          playerArr[i].hand.dequeue(catchQ);
          playerArr[i].currentHand--;
        }
    }

  //empty all deck/discard stacks
  while (!deck.isEmpty())
    deck.pop(catchPop);
  while (!discard.isEmpty())
    discard.pop(catchPop);

  //reset hand/deck counters to defaults
  catchQ = 0;
  catchPop = 0;
  currentDeck = 52;
  currentPlayer = 1;
  numPlayers = 2;

  cout << "\n\n\n\t Good Game!" << endl << endl;

  //free dynamic memory
  delete [] playerArr;

It's too late for me to change my grade on this program and with finals week I don't have time to visit my prof during office hours so if someone has a solution for me I can learn from this mistake and move on.

Thank you


Solution

  • One probable cause of the problem is that you forget that array-indexes are zero-based.

    An array of numPlayers elements will have indexes from 0 to numPlayers - 1 (inclusive).

    The first loop you show doesn't use that, instead if goes from 1 to numPlayers, leading you to index the allocated memory out of bounds which leads to undefined behavior.