In article <1a6e9f3f-3338-4acc-88e9-706ce47c3eb2@googlegroups.com>
Jarek Blakarz <jumianek@gmail.com> writes:
Hi
The following program throws an exception while allocating "A"
object. Allocation fails. An exception is caught inside "C"
constructor. "C" destructor releases memory for both objects.
Segmentation fault occurs while releasing memory for object "A"
since the memory has actually not been allocated for that object.
That isn't exactly what your problem is.
struct C {
B *ptrB;
A *ptrA;
C(void)
{
At this point, both ptrB and ptrA are uninialized pointers.
They probably have junk for values.
cout << "C" << endl;
try {
ptrB = new B;
} catch(...) {
cout << "new B - exception" << endl;
}
try {
ptrA = new A;
} catch(...) {
cout << "new A - exception" << endl;
}
If those threw, 'new' never returned, and no assignment was made,
so the pointers are still junk.
}
~C(void) {
cout << "~C" << endl;
delete ptrB;
delete ptrA;
And here, you pass junk to delete.
}
};
int main(void)
{
try {
C c;
} catch(...) {
cout << "main exception handler" << endl;
}
}
You should clear the pointers before anything has a chance of going
wrong:
C() : ptrA(0), ptrB(0)
{
// do the c'tor details
}
(Others will now tell you not to use pointers.)