Hello, I remember one thread in which I created linked list and wrote appropriate functions. Then, I had dillema how to write functions, especially how to handle memory issue. For example I thought that function that insert new item in linked list should allocate and initialize new node and then add that node in linked list structure by playing with pointers . I asked for advice and Prelude wrote this:
Now I have similar problem. I've downloaded template class AVL tree from the Internet and I want to use it to insert item, process them etc. At first I came accross one nasty run time error. Header file is in attachment because of lengthy code.Originally Posted by Prelude
By examining this code I saw this prototype:
and decide to test this tree with the following codeCode:TreeData * Insert(TreeData *item);
At the end of this program there was a run time error (exception) _BLOCK_TYPE_IS_VALID.... in dbgdel.cpp so I knew it's something fishy about memory.Code:#include "ttree.h" #include <iostream> #include <string> using namespace std; static int CMyTree_compare(const string* it1, const string* it2) { if (*it1 == *it2) return 0; else if (*it1 > *it2) return 1; else return -1; } class CMyTree : public CTTree <string> { public: CMyTree() : CTTree<string>(CMyTree_compare){} }; //} int main() { CMyTree m; string s1("Micko"); m.Insert(&s1); }
Then I tested with this code
And everything worked fine.Code:int main() { CMyTree m; string * ps1= new string("Micko"); m.Insert(ps1); }
By examining ttree.h I noticed that memory is deleted in destructor, so that's why there was an excaption at the end of the program.
Object was created on stack, passed by address and destructor try to delete it producing run time error.
So in esence this AVL tree structure is organize that way (if I'm not mistaken) that it must receive pointer to object on the heap and deallocate memory automatically. So this structure do not allocate memory but deallocate it.
I found this implementation very unintuitive to use, and since I don't have any real life programming experience I would like to ak you to comment this. If this practice usual and what do you think about this code?
Thank you very much
- Micko



LinkBack URL
About LinkBacks


