The addStudent function and mainMenu function are the two that are important.
#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);
}
Basically wondering if “delete p_students;” in the mainMenu function will properly delete all allocated memory so that the program doesn’t leak memory. Any help is appreciated, thanks a lot.
These lines will leak an instance of Student:
You allocate a Student, assign it to
p_place_holder, then later overwrite the pointer with NULL without deleting the instance.You also have:
which will overwrite
p_studentsthree times without trying to free the memory in the old value.The larger problem is you end with
delete p_students, but that won’t examine theStudentstructure to find the pointer within it, delete it, etc, recursively, as you are hoping. You are leaking almost all of the memory you’ve allocated.I think you are misunderstanding how new and delete pair together.