Reputation: 334
I delete
the pointer aStudent
in the destroyStudent()
function, then I set aStudent
to nullptr
. However, after running the function, aStudent
is not set to nullptr
anymore, so I have to set it to nullptr
again.
#include <cstring>
using namespace std;
struct Student {
char * name;
float gpa;
};
Student * createStudent(const char name[], float gpa) {
struct Student * student = new Student;
student->name = (char*)malloc(strlen(name + 1)); //allocate only enough memory to fit the given name
strcpy(student->name, name);
student->gpa = gpa;
return student;
}
bool destroyStudent(Student * aStudent) {
if(aStudent) { //check whether this pointer is already null.
free(aStudent->name);
delete aStudent; // ******This is where the issue is******
aStudent = nullptr;
return true;
}
return false; //aStudent is already null
}
int main() {
Student * student1 = createStudent("Charles", 2.5);
cout << student1->name << " and " << student1->gpa << endl;
destroyStudent(student1);
if(student1) {
cout << "Pointer is NOT null!!!" << endl;
student1 = nullptr;
}
if(!student1) {
cout << "The pointer is null now." << endl;
}
return 0;
}
Upvotes: 1
Views: 1281
Reputation: 1
C++ uses pass-by-value.
You're setting the variable local to your destroyStudent()
method to nullptr
, not the variable in your main()
.
Upvotes: 0
Reputation: 48635
The problem is that aStudent
is a local copy of the pointer.
You need to pass the pointer in by reference like this:
bool destroyStudent(Student*& aStudent) {
if(aStudent) { //check whether this pointer is already null.
free(aStudent->name);
delete aStudent; // ******This is where the issue is******
aStudent = nullptr;
return true;
}
return false; //aStudent is already null
}
That way it is the outside pointer you change, not a local copy.
Upvotes: 6