0

I have a program that has a dynamic array of Players within a Team, and a dynamic array of teams in a league. I know I could use vector, but I want to learn how to use dynamic arrays and how memory works.

When I create two team objects, I get a free(): double free detected in tcache 2 error. I ran valgrind and I commented stuff out until I deduced it was because of my destructor, but I don't know how to fix it. I get many memory leaks without the destructor.

Any help is appreciated. Here is my code in the file with the error:

#include "Team.h"
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <iomanip>

using namespace std;

Team::Team() {
   location = "";
   nickname = "";
   num_players = 0;

   maxSize = 1;
   currentSize = 0;
   players = new Player[maxSize];
}

Team::Team(const std::string &loc, const std::string &name) {
   location = loc; 
   nickname = name; 
   num_players = 0;

   
   maxSize = 1;
   currentSize = 0;
   players = new Player[maxSize];
   
}

Team::~Team(){
   if(players){
   delete [] players;}
}

void Team::grow(){
   maxSize = currentSize * 2;
   Player* newList = new Player[maxSize];

   for (unsigned i = 0; i < currentSize; i++){
      newList[i] = players[i];
   }

   delete [] players;
   players = newList;

}

void Team::addPlayer(const Player &p) {
   if (currentSize == maxSize){
      grow();
   }
   players[currentSize++] = p;

}

void Team::showTeam() const {
   std::cout << location << " " << nickname /*"(" << currentSize << " " << "players" << ")"*/ << endl;   
}

void Team::showPlayers() const {
   std::cout << "   Players:" << std::endl;
   for (unsigned int i = 0; i < num_players; i++) {
      player[i].show();
   }
}

std::ostream &operator<<(std::ostream &out, const Team &tm) {
   tm.showTeam();
   return out;
}
anon anon
  • 11
  • 1
  • 1
  • Where is your `Team::Team(Team const&)`? Where is your `Team& Team::operator=(Team const&)`? – Eljay Mar 09 '22 at 02:17
  • It is unable to detect free(): double free in the code above, because it does not have main and therefore does nothing. – 273K Mar 09 '22 at 02:18
  • Said another way from Eljay -- if you do `Team a;` and `Team b = a;` or something like that, without a copy operator (or constructor based on your code), it copies objects. In this case, the raw pointers. You now have two objects that point to the same array, and you'll thus double-delete. – Joseph Larson Mar 09 '22 at 03:59

0 Answers0