Sign in to follow this  
arock99

Custom CString class Memory Leak

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this