EXC_BAD_ACCESS during Copy Constructor

Good Evening,
I have been writing apps in C++ for a while now but I have to admit
the below problem has stumped me - I would not consider myself an
'expert' but also I am not a novice. Any help would be appreciated.
I have a copy constructor which is defined as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
Object::Object(const Object& o) { 
if (o != NULL) { 
    if (_internalObject != NULL) { 
       delete _internalObject; 
       _internalObject = NULL; 
    } 
    _message = ex.Message(); 
    if (o.InternalObject() != NULL) { 
       _internalObject = new Object(); 
       _internalObject = ex.InternalObject(); 
    } 
  } 
} 


When I get to the line that deletes the internal object (which is a
pointer that is initialized during the constructor) I get
EXC_BAD_ACCESS. I have debugged the app and I can confirm that I am
not calling a double free() and that _internalObject actually does
piont to something.
The code from which the copy constructor is initiated is below...

1
2
Object * o = new Object(); 
if (o != NULL) {Object p = *o; //etc....} 


the app only crashes when I copy the object, all other constructors
are fine. Does anyone have any ideas what may cause this?
Many thanks in advance.
Phil.
What's the point of checking that o isn't NULL? References can't be NULL.

When an object is constructed, its primitive elements (pointers, integers, etc.) are in an uncertain state. Your check on line 3 is very unlikely to be false, but _internalObject is most certainly not pointing to an object, so line 4 will always be deleting something that doesn't exist.
Solution: remove the if statement completely expect for the assignment of NULL to _internalObject.

EDIT: Also, line 10 is creating a memory leak. The object created on line 9 is now inaccessible.
Last edited on
Ok, I get it. Sorry must have been having a bit of a moment.

Thanks for the advice about line 10. Much appreciated.
Topic archived. No new replies allowed.