Linked List Help

Hey guys I am having problems with memory management...
Each time I call the createNode function I allocate memory on the heap with the temp node pointer. How can I delete this pointer to free up the memory that I needed. How can I prevent a memory leak.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>

using namespace std;

struct Node{
    int data;
    struct Node* next;
};
Node *head, *tail, *curr;

void createNode(int x);

int main()
{
    createNode(100);
    createNode(200);
    createNode(300);
    
    curr = head;
    
    while (curr!=NULL) {
        cout << curr->data << endl;
        curr = curr->next;
    }
  
    
    return 0;
}

void createNode(int x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = NULL;
    
    if (head == NULL) {
        head = temp;
        tail = temp;
    }
    else
    {
        tail->next = temp;
        tail = temp;
    }
    //delete temp;
}
You don't want to delete a "pointer". You want to delete the objects that you have dynamically allocated.

You do create objects explicitly and you don't hand their "ownership" to any "smart pointer" that would handle the deallocation automatically.

Therefore, you have to deallocate explicitly. Line 27 would be appropriate place to do it. Hint: head.
can you show me and write out for this program to have no mem leaks. please I am having trouble with memory management with linked lists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

using namespace std;

struct Node{
    int data;
    struct Node* next;
};
Node *head, *tail, *curr;

void createNode(int x);

int main()
{
    createNode(100);
    createNode(200);
    createNode(300);
    createNode(400);
    curr = head;
    
    while (curr!=NULL) {
        cout << curr->data << endl;
        curr = curr->next;
    }
    
    curr = head;
    while (curr!=NULL) {
        delete curr;
        curr = curr->next;
    }
  
    
    return 0;
}

void createNode(int x)
{
    Node* temp = new Node;
    temp->data = x;
    temp->next = NULL;
    
    if (head == NULL) {
        head = temp;
        tail = temp;
    }
    else
    {
        tail->next = temp;
        tail = temp;
    }
    //delete temp;
}
how do i delete temp?? It is out of scope on line 27 i don't know how to do this.
Your lines 26-30 are close, but ... trying to read curr->next right after the curr has been deleted is doomed.
1
2
3
4
5
6
7
8
9
curr = head;
while ( curr ) {
  Node * temp = curr;
  curr = curr->next;
  cout << "Deleting node that has value " << temp->data << '\n';
  delete temp;
}
head = nullptr;
tail = nullptr;


PS. On line 15 you do test whether head is NULL, but head is uninitialized.
Topic archived. No new replies allowed.