Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer being freed was not allocated for pointer assignment

I was trying to change a ListNode struct into a class format but am running into some issues when testing it.

Getting a.out(7016) malloc: * error for object 0x7fff65333b10: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

chainLink.hpp 
#ifndef CHAINLINK_H
#define CHAINLINK_H

using namespace std;
#include <iostream>
#include <cstdlib>

template <typename Object>

class chainLink
{
    private:
        Object storedValue;
        chainLink *nextLink;
    public:
            //Constructor
        chainLink(const Object &value = Object()): storedValue(value)
        {
            nextLink = NULL;
        }
        /* Postcondition:   returns storedValue;
         */     
        Object getValue()
        {
            return storedValue;
        }

        /* Postcondition:   sets storedValue = value
         */
        void setValue(Object &value)
        {
            storedValue = value;
        }

        /* Postcondition:   sets nextLink to &value
         */
        void setNextLink(chainLink* next)
        {
            nextLink = next;
        }

        chainLink* getNext()
        {
            return nextLink;
        }
        ~chainLink()
        {
            delete nextLink;
        }
};
#endif

My test file, assume includes

int main()
{
    chainLink<int> x(1);
    cout << "X: " << x.getValue() << " "<< endl;
    chainLink<int> y(2);
    cout << "Y: " << y.getValue() << " "<< endl;
    chainLink<int>* z = &y;
    cout << &y << " " << z << endl;
    x.setNextLink(z);
}

OUTPUT: X: 1 Y: 2 0x7fff65333b10 0x7fff65333b10 a.out(7016) malloc: * error for object 0x7fff65333b10: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6

The error seems to be thrown by the setNextLink function.

Any help greatly appreciated.

like image 664
user1645240 Avatar asked Dec 29 '25 06:12

user1645240


2 Answers

You are giving setNextLink a pointer to an automatically allocated variable,

x.setNextLink(z); // z points to automatic object y

which you attempt to delete in the constructor.

~chainLink() {
    delete nextLink; // attempts to delete automatic object y
}

You need to pass a pointer to a dynamically allocated object, or make your own insde your chainLink class.

Note: In C++, structs and classes are the same bar some differences. A equivalent types can be implemented using either of the two.

like image 100
juanchopanza Avatar answered Dec 31 '25 21:12

juanchopanza


In the last line of main you are calling setNextLink with a pointer to an object with automatic storage duration (z holds the address of y). Your list tries to delete that pointer when it is destroyed, hence the error (y has not been allocated dynamically, and hence cannot be deleted dynamically).

like image 21
Björn Pollex Avatar answered Dec 31 '25 22:12

Björn Pollex