I have the following (simplified) code. gQuickChatTree is a global vector of QuickChatNodes, which are themselves simple structs of 7 fields.
function allocate()
{
QuickChatNode node;
gQuickChatTree.push_back(node);
}
This seems to work just fine. I can read the nodes later without problem. However, when the function returns, I notice that the destructor on node is called, and, sometimes, I am experiencing heap corruption errors when I exit the program, possibly related to gQuickChatTree.
Is this code correct? Or is my node disappearing when I exit the function, only to be deallocated again when the program closes, leading to my heap corruption problem?
push_back copies the object into the vector so this is not the problem, unless in QuickChatNode you have some dynamic members and you didn't overload properly the copy constructor
Yes, it may very well be a problem. There appears to be a fundamental design problem with your tree structure.
The gQuickChatTree should either maintain a list of QuickChatNode* or you need to make sure that the QuickChatNode classes don't maintain shallow copies of dynamic memory.
If neither of those caveats apply, then your code should work fine. (The copy constructor is called on your node when you push_back().)
I don't understand the comment about "shallow copies of dynamic memory", but what it sounds like you are saying is that the destructor that is being called is in reference to the original node object, but that a copy is made when it is pushed into the vector. So, for a brief instant, there are two copies of node extant, and that the first destructor is called when the allocate function exits, and is then called a second time, on the copy, when gQuickChatTree is deleted.
Is that right?
In other words, this is not the source of my heap corruption error.
#include <iostream>
struct A{
int *a;
A(){
this->a=newint;
}
~A(){
deletethis->a;
}
/*
Default copy constructor:
A(const A &orig){
this->a=orig.a;
}
*/
};
int main(){
A *obj0=new A;
A obj1(*obj0); //obj0.a and obj1.a both point to the same place,
delete obj0; //so now obj1.a is invalid.
std::cout <<obj1; //Segmentation fault. Derefencing an invalid pointer.
}
When using std:: stuff you shouldn't worry, it does everything needed.
- So yes, strings are copied properly -
The error has to be somewhere else then...
In his code appears 'string' so I presume that stands for std::string as typedefs usually are uppercase ( and he is using a std::vector so it must be C++ )
Great, thanks. The thing of it is that I just create the items, then everything is read-only until the program closes. Well, I've got some poking around to do, I'll post back if I find anything interesting.