Heap Corruption

Hi guys, quick question ,
I cannot not follow why there is a heap corruption.

The char ptr has been allocated on the heap, copied into new object (deep copy with copy ctr) but it looks like the compiler is deleting this ptr itself once it goes out of scope ... could anyone shine some light to this please??

CRT detected that the application wrote to memory after end of heap ERROR

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
 
class AnotherClass
{

public:
	AnotherClass(char * p_chars, int size) :p_c(p_chars) , m_size(size)  {};

	AnotherClass(const AnotherClass & cp)
	{
		m_size = cp.m_size;
		char * p = new char[m_size]; // alloc mem
		
		strcpy(p, cp.p_c); // copy mem
		p_c = p;
	}

	void Print()
	{
		std::cout << p_c<< std::endl;
	}

	~AnotherClass()
	{
		delete[] p_c;
	}

private:

	char * p_c;
	int m_size;
};


int main()
{
	char * a = new char[15] {"someString\0"}; 

	AnotherClass * aNother= new AnotherClass(a,sizeof(a)) ; // alloc on heap

	AnotherClass someOtherClass(*aNother); // copy constructor

	delete aNother; // delete from heap

	someOtherClass.Print();

	system("pause");

}//someOtherClass out of scope 
You might be having a problem with line 38, sizeof( a ). Quickly try it with 15 and see if it runs better.
closed account (48bpfSEw)
yes koothkeeper, I think that could be the problem. sizeof (a) delivers the size of the pointer (4) and not the size of the array (15)
Yes that`s correct, nicely spotted. Thank you!
Topic archived. No new replies allowed.