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;
}