Stephan Vorster Stephan Vorster - 3 years ago 132
C++ Question

Linked List ostream overload weird values

I'm realitively new to using linked lists. I'm trying to overload the ostream opperator for a doubly linked list with decleration :

template <class T>
class DynamicList;

template <class T>

template <class T>
class DynamicList
{
private:

Node<T> *head;

public:
class Node
{
public:

T* value;
Node<T> *next;
Node<T> *prev;

Node(T val)
{
next = nullptr;
prev = nullptr;
value = &val;
}

};
DynamicList();
~DynamicList();


void operator+=(const T);


friend std::ostream & operator<< <>(std::ostream &, const DynamicList<T> &);
};


and function defenition:

template <class T>
ostream& operator << (ostream & out , const DynamicList<T> & rhs)
{
Node<T>* nodePtr = rhs.head;
Node<T>* nptr = nodePtr->next;
while(nodePtr != NULL)
{
cout<<*(nodePtr->value)<<" ";
nodePtr = nodePtr->next;
}
out<<endl;
return out;
}

template <class T>
void DynamicList<T>:: operator +=(const T val)
{
Node<T>* nodePtr = nullptr;
T vall = val;
Node<T>* newNode = new Node<T>(vall);
if(!head)
{
head = newNode;
}
else
{
nodePtr = head;
while((nodePtr->next))
{
nodePtr = nodePtr->next;
}
nodePtr->next = newNode;
newNode->prev = nodePtr;
}


Every time I'm calling the opperator it gives a weird output for example using:

for(int i = 1; i <= 3; i++)
{
list += i;
}
cout<<list;


It would give an output like 135727363 135727383 135727383 ,I'd just like to know what I'm doing wrong and possibly how I could solve it

Answer Source

Your problem is here:

T* value;

You are storing the address of a value.
The problem is that you are storing the address of a variable that has gone out of scope.

T vall = val;
Node<T>* newNode = new Node<T>(vall);

The variable vall is local to the function operator += which means after it exists it no longer exists (and can contain anything).

To fix change the node to store the value.

class Node 
{ 
 public:

    T        value;    // Notice no star here.
    Node<T> *next; 
    Node<T> *prev;

    Node(T const& val)      // Add `const&` here to avoid a copy.
    {
        next = nullptr;
        prev = nullptr;
        value = val;        // Notice no and `&` here
    }  

};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download