C ++ error in ': free (): invalid pointer

I've read similar problems, but I can't find anything that specifically addresses my problem (or I just don't understand other solutions)

I am trying to implement a template Stack class and I am having a problem when trying to push onto the stack. here is my Stack.cpp:

#ifndef _STACK_H
#define _STACK_H

#include <string>
#include <stdio.h>
#include "Node.cpp"

template<typename T>
class Stack{
    private:
        Node<T>* mHead; 

    public:
        Stack();
        ~Stack();
        void push(T data);
};

template<typename T>
Stack<T>::Stack(){
    mHead = NULL;
}

template<typename T>
Stack<T>::~Stack(){
    delete mHead;
}

template<typename T>
void Stack<T>::push(T data){        // <-- having trouble with this method
    Node<T>* temp = new Node<T>;
    temp->data = data;
    //if head is already empty, just create 1 Node
    if(mHead==NULL){
        printf("if working\n");
        mHead = temp;
    }else{
        printf("else working\n");
        //rearrange Nodes
        temp->next = mHead;
        mHead = temp;
    }
    printf("success\n");
}

#endif

      

push () is called from a function in the manager class:

void Manager::testPush(){
    Stack<int> test;
    int number = 3;
    test.push(3);
}

      

When I run the testPush () method to manage code and calls, I get this:

if working
success
*** Error in `./assignment': free(): invalid pointer: 0x0000000000f11078 ***
[1]    14976 abort (core dumped)  ./assignment

      


I'm not sure what free () means and what might be causing this error / abort

+3


source to share


1 answer


It seems like you forgot to set the data member next to NULL in node temp.

template<typename T>
void Stack<T>::push(T data){        // <-- having trouble with this method
    Node<T>* temp = new Node<T>;
    temp->data = data;
    temp->next = NULL; // <=== add this statement

    //if head is already empty, just create 1 Node
    if(mHead==NULL){
        printf("if working\n");
        mHead = temp;

      

If the node class has a constructor with two parameters, or if it is an aggregate, you can write a simpler one

template<typename T>
void Stack<T>::push( const T &data )
{
    mHead = new Node<T> { data, mHead };
}

      



Note that the destructor of the node class must remove all nodes on the stack.

This function

void Manager::testPush(){
    Stack<int> test;
    int number = 3;
    test.push(3);
}

      

also looks questionable because test is a local variable of the function. The stack can only be used inside a function.

+5


source







All Articles