addStudent函数和mainMenu函数是重要的两个函数。
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
string major;
Student *p_next;
};
Student *addStudent(Student *p_students)
{
Student *p_new_student = new Student;
cout << "Student name: \n";
cin >> p_new_student->name;
cout << p_new_student->name << "'s major: \n";
cin >> p_new_student->major;
Student *p_place_holder = new Student;
Student *p_all_students = new Student;
p_all_students = p_students;
p_place_holder = NULL;
if (p_students == NULL) // Adds the first element to the linked list which was initialized to NULL
{
p_new_student->p_next = p_students;
delete p_place_holder;
delete p_all_students;
return p_new_student;
}
else // Adds elements beyond the first element to the linked list
{
while (p_all_students != NULL)
{
if (p_new_student->name.compare(p_all_students->name) <= 0)
{
if (p_place_holder == NULL) /* if p_new_student->name is before
p_all_students->name and p_all_students is still the first element in the list*/
{
p_new_student->p_next = p_all_students;
p_all_students = p_new_student;
delete p_place_holder;
return p_all_students;
}
else
{
p_new_student->p_next = p_all_students;
p_place_holder->p_next = p_new_student;
return p_students;
}
}
else if (p_new_student->name.compare(p_all_students->name) > 0)
{
p_place_holder = p_all_students;
p_all_students = p_all_students->p_next;
}
}
}
}
void mainMenu(Student *p_students)
{
int response = 0;
cout << "1. Add Student\n";
cout << "2. View Students\n";
cin >> response;
if (response == 1) // calls addStudent 4 times and then mainMenu
{
p_students = addStudent(p_students);
p_students = addStudent(p_students);
p_students = addStudent(p_students);
p_students = addStudent(p_students);
mainMenu(p_students);
}
else if (response == 2) // lists the students and their majors and then exits
{
while (p_students != NULL)
{
cout << p_students->name << '\n';
cout << p_students->major << "\n\n";
p_students = p_students->p_next;
}
}
delete p_students; // hopefully deletes all allocated memory
}
int main()
{
Student *p_students = new Student;
p_students = NULL;
mainMenu(p_students);
}
基本上想知道“删除p_students;”在mainMenu函数中将正确删除所有已分配的内存,以便程序不会泄漏内存。感谢任何帮助,非常感谢。
答案 0 :(得分:6)
这些行会泄漏Student的实例:
Student *p_place_holder = new Student;
Student *p_all_students = new Student;
p_all_students = p_students;
p_place_holder = NULL;
您分配学生,将其分配给p_place_holder
,然后稍后用NULL覆盖指针而不删除实例。
您还有:
p_students = addStudent(p_students);
p_students = addStudent(p_students);
p_students = addStudent(p_students);
p_students = addStudent(p_students);
将覆盖p_students
三次而不试图释放旧值中的内存。
更大的问题是你以delete p_students
结束,但是这不会检查Student
结构以查找其中的指针,删除它等,递归地,正如您所希望的那样。您几乎泄漏了所有已分配的内存。
我认为你误解了新的和删除对的结合。
答案 1 :(得分:0)
您必须使用强制所有权指针来避免内存泄漏 - 例如,unique_ptr
和shared_ptr
。您永远无法使用delete
来有效防止泄密。