I have a problem about memory allocated, I read through my code and think threre is no problem, but it did happens, it very confusing me ...., here is my code: the problem lies in a[] when the Class Grid
GridUnit has a pointer to the array, a. The memset in Grid's constructor is overwritting a with null. Later on, you try to index an array starting at 0.
why tmp reference is not appropriate here? Can you explain it for me? I really don't know why, because after removing the superfluous initialization, the code runs well.
Also overwriting a class object using memset like that can trash the object (for example - it
can destroy the VFT pointer).
If a class contains virtual functions then there is a hidden pointer which is stored along with objects of that class that points to the virtual function table. So there is more to a class/object than just the data and functions that you defined for it.
If you trash this pointer then a crash will happen when you try to call a virtual function:
class base
{
public:
virtualvoid doSomething(void) {cout << "Hello from Base" << endl;}
};
class derived :public base
{
public:
void doSomething(void) { cout << "Hello from Derived" << endl;}
};
int main()
{
base bb;
derived dd;
base *pbase;
memset(&dd,0,sizeof(dd) ); //oops! overwriting derived class object
pbase = ⅆ //base pointer pointing to derived class
pbase->doSomething(); //virtual function call in action - should crash
return 0;
}