heap corruction after "[] delete"

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
#include "stdafx.h"
#include <iostream>
#include "BinarySearchTree.h"
using namespace std;
    // Test program

template <class T>
class storage
{
public:
	T m_data;
	storage( T t ):m_data(t) {};
	
	~storage(){}
 	void print() { cout<<m_data<<endl; }
};
storage<char*>::storage(char* y)
{
	m_data = new char( strlen(y)+10 );
	m_data = strcpy(m_data, y);
	printf("m_data size is %d\n", strlen(m_data) );
}
storage<char*>::~storage()
{
	if( m_data )
		delete m_data;
}


int main( )
{
	storage<int> m(3);
 	m.print();
    
	char *x = new char[20];
	cout<<"input your name"<<endl;
	cin>>x;

	cout<<"output: "<<endl;
	storage<char*> ch(x);
	ch.print();
	return 0;
}



Got Heap Corruption error message after running it. I know it's caused by
1
2
3
4
5
storage<char*>::~storage()
{
	if( m_data )
		delete m_data;
}
after this destructor is called at the end of main().

But don't know why... Please help~ Thank you very much!
1
2
m_data = new char( strlen(y)+10 );
m_data = strcpy(m_data, y);


These lines are causing memory corruption. I think you meant:

1
2
m_data = new char[ strlen(y)+10 ];
m_data = strcpy(m_data, y);


You will also need to change your destructor to use the correct delete type, but I'll let you go look that up. ;)
You also need to implement a copy constructor and assignment operator for storage<char*>.
Firedraco, thank you for pointing this out! I don't know why I made such a silly mistake. For the destructor I need to change to
delete [] m_data;
, right? One further question is: is it always correct to use delete [] ptr? I made the following code
1
2
3
int *p = new int;
*p = 3;
delete [] p;

and it seems to run right.



Jsmith, thanks for your suggestion. Maybe my understanding is not right, but is the following a copy constructor?
1
2
3
4
5
6
storage<char*>::storage(char* y)
{
	m_data = new char( strlen(y)+10 );
	m_data = strcpy(m_data, y);
	printf("m_data size is %d\n", strlen(m_data) );
}


Also I tried to implement a = operator like this:
1
2
3
4
5
6
7
storage<char*> & storage<char*>::operator=(const char*  &y)
{
	m_data = new char[strlen(y)+1];
	m_data = strcpy(m_data, y);
	printf("m_data size is %d\n", strlen(m_data) );
	return (*this);
}


But there is a compilation error. I think the declaration must be wrong, but I don't know where goes wrong ( I am still a bit confused by the rules of template ). Would you please point it out?

Thank both of you very much!
Last edited on
A copy constructor would look like this for your class:

storage<char*>::storage(const storage<char*>& other)

What is the error you get on your = operator?
The assignment operator would have signature

 
storage<char*>& storage<char*>::operator=( storage<char*> rhs );

Got it! Thank you both very much!
Topic archived. No new replies allowed.