I got a problem of double free or corruption (fasttop)

As title, I got a problem which I can't figure out why
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdio>
class v{
	public:
	int* data;
	v(){data = new int[2];}
	~v(){delete[] data;}
};
int main(){
	v a;
	a.data[0] = 1;
	a.data[1] = 3;
	{
		v tmp = a;
		for(int i = 0;i < 2;i++) tmp.data[i] += i*i;
	}
	a.data[1] = 5; //in this line, where the problem occurs
	printf("%d", a.data[1]);
	return 0;
}
The problem is that the copy constructor created implicitly by the compiler simply copies members of the class. So after the statement

v tmp = a;

the both objects tmp and a point to the same memory region addressed by member data.
Object tmp has a block scope because it is defined within a compound statement

1
2
3
4
	{
		v tmp = a;
		for(int i = 0;i < 2;i++) tmp.data[i] += i*i;
	}


After exiting this block scope object tmp will be destroyed. It means that will be called its destructor that frees memory pointed by data. So the value in data of obejct a becomes invalid: the memory region was freed. But you are trying to access it

a.data[1] = 5; //in this line, where the problem occurs

And this is the result of the corruption.
Last edited on
Oh!

I seeee~

Thanks for your help!
Topic archived. No new replies allowed.