I am unable to find out the bug in the below code which i had written[Not for any purpose though].
#include < iostream >
#include < cstdlib >
using namespace std;
class Base{
public:
Base(){cout << "Base class constructor" << endl;}
void funv() {};
~Base(){cout << "Base class destructor" << endl;} ;
};
class Derived:public Base{
public:
char *ch;
Derived():ch(new char[6]()){}
~Derived(){
cout << "before" << endl;
delete [] ch;
ch = NULL;
cout << "after" << endl;
}
};
int main(){
Derived * ptr = new Derived;
//memcpy(ptr -> ch,"ar\0",4); // Works when class Derived is derved from base and also when not derived from base
ptr -> ch = const_cast < char* >("ar0"); // Works only when class Derived is not derived from class Base
cout << ptr -> ch[1] << endl;
ptr -> funv();
delete ptr;
return 0;
}
I have commented on the suspected lines of the code.
I am using sun Studio 12.
This is an Undefined behavior. It will cause problem in any case, whether you derive it or not.
When you assign a
const char*to achar*like below:That means, you are assigning a character string which is defined in non-heap segment (mostly in data segment). One should only
deletememory which was allocated on heap segment.Also, above assignment statement is executed, it will leak memory pointed by
chearlier. One way to avoid such problem is to declare the variable as,As soon as you try assigning something to
ch, it will give compilation error. So that it will make you write wrapper to assignchand there you can take care of deallocation.