deepzero Posted February 11, 2011 Posted February 11, 2011 (edited) 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, 2011 by deepzero
Killboy Posted February 11, 2011 Posted February 11, 2011 unless your compiler is broken (which I doubt), it should call its destructor.maybe it's because you don't have a copy constructor?
deepzero Posted February 11, 2011 Author Posted February 11, 2011 (edited) forgot to mention that i am using MSVC++ 2008. what do you mean by "copy constructor"? edit: *no, wrong* Edited February 11, 2011 by deepzero
Killboy Posted February 11, 2011 Posted February 11, 2011 "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
deepzero Posted February 12, 2011 Author Posted February 12, 2011 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.
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now