Problem with the heap

The program compiles fine, it just gives me an error: Heap Corruption Detected. I appreciate any help.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
30
31
32
33
34
35
36
#include <iostream>
using namespace std;
class Person
{
	char *name;
	char *surname;	
public:
	Person(char *name,char *surname)
	{
		Person::name=new char[strlen(name)+1];
		Person::surname=new char[strlen(surname)+1];
		strcpy(Person::name,name);
		strcpy(Person::surname,surname);
	}
	Person& operator=(const Person& ob1)
	{
		delete name;
		delete surname;
		name=new char[strlen(ob1.name)+1];
		name=new char[strlen(ob1.surname)+1];
		strcpy(name,ob1.name);
		strcpy(surname,ob1.surname);
		return *this;
	}
	~Person()
	{
		delete name;
		delete surname;
	}
};
int main(int argc,char* arguments[])
{
	Person ob1("john","doe");
	Person ob2("alex","me");	
	ob1=ob2;
}
You need to use the delete[] form of delete. Also, you need to guard against self-assignment in you operator=.
By self-assignment you are reffering if i wrote ob1=ob1 in main?
That be what is meant.
I also think that line 20 is supposed to be changing surname, not name
thanks.Everything is now ok.
Topic archived. No new replies allowed.