Wednesday 28 December 2016

Memory leak caused by function in C++

there is a function which creates new memory and is used in constructor.
However, I do not know how to access it in destructor to delete it.



In constructor is used (same file) player.cpp



#include 

#include "Player.h"


// TODO: Fix the bugs in this file

Player::Player(const char* name) : name_(0)
{
copyString(&name_, name);
}

Player::Player(const Player& copy) : name_(0)
{
name_ = copy.name_;

}

Player::~Player()
{
delete [] name_; // Not sure if it works. errors promts- double free
}

Player& Player::operator=(const Player& copy)
{
return *this;

}

void Player::copyString(char** dest, const char* source)
{
unsigned int str_len = strlen(source);
char* str = new char[str_len+1]; //This line
strncpy(str, source, str_len);
str[str_len] = '\0';

*dest = str;

}

std::ostream& operator<<(std::ostream& out, const Player& player)
{
out << player.name_ << std::endl;
return out;
}


All i am allowed to change are .cpp files.

I have added delete line i destructor, but error shows up.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...