Jump to content
Tuts 4 You

custom string class: memory leak


Recommended Posts

hi guys,

i was trying to implement a custom string class for practicing purposes,

but i hit a problem regarding memory leaks...

to be more precise, the problem is the substring-method:

substr(int start, int length);

to be used like this:

mystring a = "deepzero";
mystring b = a.substr(4,4);//b == "zero"



the problem is: when i create the substring, where do i store it?

When i allocate space on the heap, it wont be freed anymore...

So i figured i`d have .substr() return a mystring object (containing the substring):

mystring mystring::substr(int start,int len)
//ptrtostr == pointer to the actual char-array which stores the text
//mystring-constructor takes a pointer and assigns the number of bytes in len to the new text string
return mystring((this->ptrtostr + start),len);//

That way, the constructor would allocate the memory for the substring and the destructor would free it again.

Or so I thought...

i was using this to test it:

int main()
mystring test = "deepzero";
mystring test2 = test.substr(1,3);//==eep

and it works fine, but unfortunately the mystring-object i return from the substr() function

never calls its destructor... :(

why not? :(

how would you solve the substring-problem ?


dp0 :)

Edited by deepzero
Link to comment

forgot to mention that i am using MSVC++ 2008. :)

what do you mean by "copy constructor"?


*no, wrong*

Edited by deepzero
Link to comment

"no, wrong" as in: you do have a copy constructor?

how do you know it doesn't call the destructor?

i mean, if you have a copy constructor, this should work fine without memory leaks. if you don't, the default one performs shallow copies on the heap pointers, making them all share the same memory, and only that one chunk gets freed.

otherwise, i dont see a problem with your code :s

Link to comment

hi killboy,

after cleaning the code a little bit & sleeping over it, it works now.

No idea what exactly went wrong...but i love it when my problems dissolve into thin air over night... :sweat:

thanks for your time. :)

Link to comment

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
  • Create New...