Search code examples
c++dynamic-memory-allocationdelete-operator

Multiple uses of new and delete


I'm simulating a traditional card game between two players using C++: I defined a "card" structure so that

card sample;
cout << sample.numb << " of " << sample.suit << " ownded by player " << sample.own

reads e.g. "10 of spades is owned by player 2".

I set up a vector "deck" (of size 40) keeping track of every card, and I'm dynamically allocating vectors "g1" "g2" and "tab" at every step of the game, in order to handle player 1's hand, player 2's hand and cards on the table with three separated objects (this is kind of necessary for the game itself).

Since the players keep putting cards on the table and gaining/losing new cards the sizes keep changing, so every time I do something like this:

delete g1;
delete g2;
delete tab;
n1=count (1,deck);  // this counts how many cards in "deck" have .own field==1
n2=count (2,deck);  // this counts how many cards in "deck" have .own field==2
nt=count (0,deck);  // cards having .own field == 0 are on the table
g1 = new card [n1];
g2 = new card [n2];
tab = new card [nt];
k=0;               // using this to move through the vectors I just re-allocated
for (i=0;i<40;i++) {
  if(deck[i].own==1) {
     g1[k]=deck[i];
     k++;
  }
}
// then I fill "g2" and "tab" pretty much in the same way

The script compiles and runs, but after a couple of rounds (carried out correctly) I get "invalid next size (fast)" and a segfault. Reading around I found out that this usually happens when you try to delete something twice or the likes of it. My script doesn't delete anything twice, but I suspect that such a frequent use of new-delete-new is deprecated and might be the cause of my problem.

Thoughts?

EDIT I solved my issue using std::vector, I suggest doing the same to anyone ever having the same problem; thanks to everyone who answered.

Peace,

Tom


Solution

  • You'd better use array deletion for g1, g2 and tab: eg: delete [] g1;

    Of course, you're far better off using std::vector and not handling the memory management directly yourself.