copy constructor error

Hi All,
What Am I doing wrong ? because as soon as the COPY CONSTRUCTOR is called at IntArray e(c). More specifcally, at this line arrayPtr = obj.arrayPtr; I get "*** glibc detected *** /home/nhat/workspace/IntArray/Debug/IntArray: double free or corruption (fasttop): 0x0937c178 ***"
I just need some directions as to what could be causing this error in this situation.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
test6() {
    IntArray c(2, 10);
    for(int i = c.low(); i <= c.high(); i++)
        c[i] = i * 10;
    c.setName('c');
    cout << c << endl;

   IntArray e(c);
   e.setName('e');
   cout << e << endl;
    wait();
}

//COPY CONSTRUCTOR
IntArray::IntArray(const IntArray &obj) {
	// make a copy of obj.

	arrayPtr = obj.arrayPtr;
	lowIdx = obj.lowIdx;
	highIdx = obj.highIdx;
	indexSize = obj.indexSize;
	ptrIncrement = 0;
}


// DESTRUCTOR
IntArray::~IntArray(){
	delete [] arrayPtr;
}
Last edited on
Loops like the copy constructor is doing a shallow copy instead of a deep copy.

Your non-copy constructor is allocating a buffer. We'll call this buffer "foo" even though it's nameless.

Your 'c' object has a pointer "arrayPtr" which points to this "foo" buffer.

Now.. when you create your 'e' object, it is copy constructed. Your copy constructor does not allocate a new buffer... but instead just has e.arrayPtr set to c.arrayPtr. Since c.arrayPtr points to "foo", this means that e.arrayPtr will also point to "foo".

The problem now is when 'c' goes out of scope and its destructor is run, it will delete[] arrayPtr. Remember that delete does not delete the pointer... but rather it deletes what the pointer points to. So in this case, it will delete "foo".

Now that "foo" is deleted, it no longer exists. This is a problem because your 'e' object is still pointing to it, and it thinks it's still there. So now when 'e' is destroyed, and its destructor is run... it attempts to delete "foo" again, which will cause your program to explode because you can't delete something that no longer exists.



EDIT:

a simpler example:

1
2
3
4
5
6
7
8
9
10
11
int* a = new int;  // 'new' creates a new int ("foo") and returns a pointer to it.
int* b = a;  // your "copy constructor" is just assigning a pointer

// at this point, both 'a' and 'b' point to the same memory:  "foo"

delete a;  // since 'a' points to foo, this deletes "foo".  Foo no longer exists

// since 'b' pointed to foo, and since foo no longer exists.. 'b' now is a bad pointer
//  (it points to garbage)

delete b;  // trying to delete garbage -- EXPLODE 
Last edited on
thanks...helped.
Topic archived. No new replies allowed.