Just in case anyone comes across this the problem was.. [from my perspective and someone feel free to correct me if I am wrong]
The pointer my destructor was attempting to delete was a pointer that was allocated with memory on the stack.
1 2
|
char *username "foo"; // from main.cpp
|
Then I passed the string created in main.cpp to my class.
|
newPlayer->set_userName ( username );
|
and my class would handle the above operation as below.
1 2 3 4
|
void Player::set_userName ( char *a_userName )
{
usersName = a_userName;
}
|
and this was just creating a pointer to the same data that my original pointer pointed to.
then (not sure if my original post shows this) when (if) my destructor ran on the data member inside of my class, my compiler would complain I am trying to "free" a object that is not allocated or as cire said
Because the object you create is never destroyed and the memory used to store it is leaked. This is probably a good thing since your destructor tries to delete something your class instance doesn't own. |
as shown below
1 2 3 4 5
|
Player::~Player()
{
delete ;
}
|
What I did to fix the above issue(s) is I changed
1 2 3 4
|
void Player::set_userName ( char *a_userName )
{
usersName = a_userName;
}
|
to what is listed below. So that the string that I was passing into my class was actually copied to the memory my pointer inside of my class was pointing to.
1 2 3 4 5 6 7 8
|
void Player::set_userName ( char *a_userName )
{
if (this->usersName) {
delete [] this->usersName;
}
this->usersName = new char[strlen(a_userName)+1];
strcpy(this->usersName, a_userName);
}
|
then I changed my destructor (added a simple test statement as things were working as expected and I was no longer troubleshooting) where I think my original destructor would of worked also.
1 2 3 4 5 6
|
Player::~Player()
{
if (usersName) {
delete [] usersName;
}
}
|