Why does my program crash when deleting a pointer in the destructor?

Hello!
I can´t understand why this program crashes.
In main(), I declare char *name = new char; and pass it as argument in the Person constructor.
When deleting the Person pointer in main(), the Person destructor is beeing called and the name attribute (which is a pointer) pointing at the char, I assume, is also beeing deleted. But why does it crash?
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
#include <iostream>

using namespace std;

class Person {
private:
	char *name;
	int age;
public:
	Person(char *n, int age) {
		this->name = n;
		this->age = age;
	}
	~Person() {
		cout << "Deleting person" << endl;
 		delete name;
	}

	void setName(char *name) {
		this->name = name;
	}
	
	char *getName() {
		return this->name;
	}

	void setAge(int age) {
		this->age = age;
	}
	
	int getAge() {
		return this->age;
	}

};

void modifyPerson(Person *p) {
	cout << "Age: " << p->getAge() << endl;
	p->setAge(23);
	cout << "Age: " << p->getAge() << endl;
	cout << "Name: " << p->getName() << endl;
	char name = 'b';
	p->setName(&name);
	cout << "Name: " << p->getName() << endl;
}

int main() {
	char *name = new char;
	*name = 'a';
	Person *person = new Person(name, 30);
	modifyPerson(person);
	delete person;
	return 0;
}
You can only delete a pointer that is, or has the same value as, a pointer that was returned by a new.

You are trying to delete a pointer that was not returned by a new.

The pointer you're trying to delete is pointing to the char allocated by this line of code:
char name = 'b';
and the pointer itself was created like this:
p->setName(&name);
and then stored like this:
this->name = name;
The pointer thus is not pointing at memory allocated using new.
Last edited on
Oh, I see!

But let´s that a class deletes a member that is a pointer like the example above.
Is it up to the programmer to send a pointer returned by new and not a local pointer?

Are there any best practices on this?
Last edited on
Is it up to the programmer to send a pointer returned by new and not a local pointer?

Yes.

Are there any best practices on this?

As always, there is only opinion. Mine is that you should use new only when you have to, and prefer self-sizing C++ containers over manual use of new.
Last edited on
Topic archived. No new replies allowed.