a source code with trouble

hi:
I have a source code below,I can compile it with no error,but when I run it ,a error jump out call:"debug assertion failed".I don't know where the wrong occurs.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    #include<iostream>
using namespace std;

class Vector
{
    int size;
	int *buffer;
public:
	Vector(int s = 100);
	int& elem(int ndx);
	void display();
	void set();
	~Vector();

};

Vector::Vector(int s)
{
    buffer = new int[size = s];
	for(int i=0;i < size;i++)
		buffer[i] = i*i;

}

int& Vector::elem(int ndx)
{

    if(ndx <0 || ndx >= size)
	{
       cout << "error in index" << endl;
       exit(1);
	}
    return buffer[ndx];

}

void Vector::display()
{
     for(int j=0;j < size;j++)
		 cout << buffer[j] << endl;
}

void Vector::set()
{
    for(int j=0;j < size;j++)
		buffer[j] = j+1;

}

Vector::~Vector()
{
 
       delete[] buffer;
}

int main()
{
    Vector a(10);
	Vector b(a);
	a.set();
	a.display();

}
Off the top of my head, the default copy constructor is doing a shallow copy of the buffer pointer. So the destructor of a and b are both trying to delete the same memory.

Option 1) Comment out line 59.
Option 2) Comment out line 53.
Option 3) Implement an appropriate copy constructor.
1
2
3
Vector::Vector(int s)
{
    buffer = new int[size = s];
Don't do that. You really should initialise size properly in line of its own or preferably an initialiser list.

The problem is you're doing a copy (via a copy constructor) and you haven't defined one and the default is not appropriate.
Last edited on
Topic archived. No new replies allowed.