Ended the memory leak
This commit is contained in:
18
Q1.c
18
Q1.c
@@ -22,11 +22,6 @@ Student *create_student(int id, char *name, double grades) {
|
|||||||
// Insert student at end of the list
|
// Insert student at end of the list
|
||||||
Student* insert_student(Student *head, int id, char *name, double grades) {
|
Student* insert_student(Student *head, int id, char *name, double grades) {
|
||||||
Student *new_student = create_student(id, name, grades);
|
Student *new_student = create_student(id, name, grades);
|
||||||
if(new_student == NULL) {
|
|
||||||
printf("Creation of Student failed\n");
|
|
||||||
return new_student;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// If the list is empty, the new student we are inserting becomes the start
|
// If the list is empty, the new student we are inserting becomes the start
|
||||||
if(head == NULL) {
|
if(head == NULL) {
|
||||||
@@ -53,7 +48,7 @@ void print_students(Student *head) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Student* find_highest(Student *head) {
|
Student* find_highest(Student *head) {
|
||||||
if(head == NULL) { return NULL; } // Just exit if the list doesnt exist
|
if(head == NULL) { return NULL; } // Just exit if the list doesn't exist
|
||||||
|
|
||||||
Student *highest = head;
|
Student *highest = head;
|
||||||
Student *temp = head;
|
Student *temp = head;
|
||||||
@@ -67,6 +62,16 @@ Student* find_highest(Student *head) {
|
|||||||
return highest;
|
return highest;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// To end the memory leaks
|
||||||
|
void free_student(Student *head) {
|
||||||
|
Student *temp;
|
||||||
|
while(head != NULL) {
|
||||||
|
temp = head;
|
||||||
|
head = head->next;
|
||||||
|
free(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
Student *head = NULL; // Initialize the start of the linked list
|
Student *head = NULL; // Initialize the start of the linked list
|
||||||
@@ -80,6 +85,7 @@ int main() {
|
|||||||
Student *highest_student = find_highest(head);
|
Student *highest_student = find_highest(head);
|
||||||
printf("The highest student is %s, with a grade of: %0.02f", highest_student->name, highest_student->grades);
|
printf("The highest student is %s, with a grade of: %0.02f", highest_student->name, highest_student->grades);
|
||||||
|
|
||||||
|
free_student(head);
|
||||||
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user