Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I am trying to implement a template Stack class, and am having an issue when trying to push to 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() gets called from a function in the manager class:

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

When I run the code and call managers testPush() method, i get the following being printed:

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 could possibly be causing this error/abort

like image 372
Vaderico Avatar asked May 26 '15 06:05

Vaderico


1 Answers

It seems that you forgot to set 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 class Node has a constructor with two parameters or if it is an aggregate you could write simpler

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

Take into account that the destructor of class Node must delete all nodes in the stack.

This function

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

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

like image 140
Vlad from Moscow Avatar answered Sep 30 '22 00:09

Vlad from Moscow