Home > Software engineering >  C Linked List from header file is resetting memory storage
C Linked List from header file is resetting memory storage

Time:02-21

So I've been working on a linked list in C through a header file. When I insert values into it, it works fine, but as soon as I return to the main class and try to print the value stored inside a node, it returns a negative number. Here is an excerpt of my code so far, I tried to keep it as simplistic as possible.

This is the header file that contains the code for the linked list.

#pragma once
#include <iostream>
using namespace std;
template <typename T>
class LinkedList {

public:
struct Node {
    T data;
    struct Node* next;
};
Node* head;

void AddHead(const T& addData) {
    Node n;
    n.data = addData;
    n.next = head;
    head = &n;
    Print();
}

void Print() {
    cout << head << " " << (*head).data << endl;
}

private: 

};

And here is the reference from main.

LinkedList<int> l = LinkedList<int>();
int i = 5;
l.AddHead(i);
l.Print();

Now I thought this would work fine, but apparently something happens between when the node is added, when the program returns out of the header file, and when it prints again. I put in a second print statement inside to show the difference.

As it stands the output looks like this:

0000004F9A8FF7F8 5

0000004F9A8FF7F8 -1464607816

So at the same memory address, the value stored inside changes? I don't know what I'm doing wrong and I appreciate any help.

CodePudding user response:

void AddHead(const T& addData) {
    Node n;
    n.data = addData;
    n.next = head;
    head = &n;
    Print();
}

Once AddHead ends n is released, its a temorary variable on the stack. You have to create the nodes on the heap

void AddHead(const T& addData) {
    Node *n = new Node();
    n->data = addData;
    n->next = head;
    head = n;
    Print();
}

And next advice. dont use naked pointers, use std::shared_ptr or std::unique_ptr.

  • Related