c++ - Code giving SEG FAULT only when the class is being derived! -
unable find out bug in below code had written[not 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 derved base , when not derived base ptr -> ch = const_cast < char* >("ar0"); // works when class derived not derived class base cout << ptr -> ch[1] << endl; ptr -> funv(); delete ptr; return 0; }
have commented on suspected lines of code.
using sun studio 12.
this undefined behavior. cause problem in case, whether derive or not. when assign const char*
char*
below:
ptr -> ch = const_cast < char* >("ar0");
that means, assigning character string defined in non-heap segment (mostly in data segment). 1 should delete
memory allocated on heap segment.
also, above assignment statement executed, leak memory pointed ch
earlier. 1 way avoid such problem declare variable as,
private: char* const ch;
as try assigning ch
, give compilation error. make write wrapper assign ch
, there can take care of deallocation.
Comments
Post a Comment