|
-
November 15th, 2016, 04:40 PM
#1
Linked-List: Memory Leaks still occuring.
My code is fully functional if memory leaks are ignored but since I am dealing with dynamic allocation. For every new object created that same object must be destroyed after the task is complete
I am running my script on the GL server via Putty.
I am using the linux command: "valgrind" to check if there are any memory leaks in my code. Unfortunately there are.
Code below:
Code:
#include <iostream>
#include <string>
using namespace std;
//Constants for our for loop
const int START = 0;
const int END = 10;
//Our node structure
struct Node {
int num;
Node * next;
};
//Prototype for our recursive function
void printList(Node* &ptrNode, int direction);
int main (){
//Creating a new pointer to the head of our linked list
Node * head = NULL;
//For loop that builds our linked list with 0-9
for(int i = START; i < END;i++){
if (head == NULL){
Node* newNode = new Node();
head = newNode;
newNode->num = i;
}
else{
Node* newNode= new Node();
newNode->num = i;
newNode->next = head;
head = newNode;
}
}
//Because we don't have a "linked list" we need to pass the head
Node * ptrNode = head;
//First try we are going to go through the linked list starting at 0
cout << "Forward" << endl;
printList(ptrNode, 1);
//Second try we are going to go through the linked list starting at 9
cout << "Backward" << endl;
printList(ptrNode, 0);
//Empties Linked List so there is no memory leak
//PART 2 - Write the while loop to clear out the linked list
//temporary node to store first node
Node *temp = ptrNode;
while(ptrNode != NULL){
//temp equals to ptrNode = head, where head is initially NULL
ptrNode = ptrNode->next; //traverse through the Linked list
delete temp; //delete temp node
temp = NULL; //set the temp node to NULL so we don't lose info
}
return 0;
}
void printList(Node* &ptrNode, int direction){
//PART 1 - Write the code to recursively print the linked list
//Direction indicates forward or backward (0 or 1)
Node *temp;
if(ptrNode->next == NULL){
return; //Exit function
}
else if(direction == 1){
printList(ptrNode->next, direction); //Recursive function to traverse forward
cout << ptrNode->num << endl; //Print next value in the linked list
}
else if(direction == 0){
//Print out the last number in linked list
//first after sorting in descending order
cout << ptrNode->num << endl;
printList(ptrNode->next, direction);
temp = ptrNode->next;
temp->next = ptrNode;
ptrNode->next = NULL;
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|