Jump to content
  • Advertisement
Sign in to follow this  
arock99

Custom CString class Memory Leak

This topic is 4976 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, The following code seems to work fine: CString *test; while (true) { test = new CString("Test"); delete test; } But when I put "CString *test" within the loop: while (true) { CString *test = new CString("Test"); delete test; } I get a memory leak. Anyone have any idea why? First of all I realise I shouldn't be declaring CString within the loop, it is only like this for testing purposes as I'm actually trying to figure out why i have a memory leak somewhere else in the program and I figured CString was the most likely culprit. My Constructor & Destructor for CString are: CString::CString(char *initialStr) { str = new char[strlen(initialStr+1)]; strcpy(str, initialStr); } CString::~CString() { delete str; } str is declared as: char *str; Thank you!

Share this post


Link to post
Share on other sites
Advertisement
Release memory allocated by new [] with delete [].
Release memory allocated by new with delete.
Release memory allocated by malloc/calloc/realloc with free.

Add copyconstructor and assignment operator.

Share this post


Link to post
Share on other sites
Quote:
Original post by dalleboy
Release memory allocated by new [] with delete [].


CString::~CString() {
delete [] str; // notice the []
}

Share this post


Link to post
Share on other sites
Quote:
Original post by arock99
CString::CString(char *initialStr) {
str = new char[strlen(initialStr+1)];
strcpy(str, initialStr);
}

That should read:
CString::CString(char *initialStr) {
str = new char[strlen(initialStr) + 1]; // notice strlen(...) + 1.
strcpy(str, initialStr);
}

Share this post


Link to post
Share on other sites
Quote:
Original post by dalleboy
Quote:
Original post by arock99
CString::CString(char *initialStr) {
str = new char[strlen(initialStr+1)];
strcpy(str, initialStr);
}

That should read:
CString::CString(char *initialStr) {
str = new char[strlen(initialStr) + 1]; // notice strlen(...) + 1.
strcpy(str, initialStr);
}


Good catch! I'm kinda surprised i wasnt getting some sort of exception because of this.

Thanks!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!