Posted February 11, 201114 yr 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" or MessageBox(0,a.subtr(4,4),"test",0); 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 ? br, dp0 Edited February 11, 201114 yr by deepzero
February 11, 201114 yr unless your compiler is broken (which I doubt), it should call its destructor.maybe it's because you don't have a copy constructor?
February 11, 201114 yr Author forgot to mention that i am using MSVC++ 2008. what do you mean by "copy constructor"? edit: *no, wrong* Edited February 11, 201114 yr by deepzero
February 11, 201114 yr "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
February 12, 201114 yr Author 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... thanks for your time.
Create an account or sign in to comment