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.
newsomewhere. Everydeletecall must be preceded by anewcall somewhere (which may or may not be somewhere outside your code). - In silicozpointer from a call to new? - MatObject. At first I thought it was JAVA code. In C++ it is common to useTas intemplate <typename T>. Also method names typically start with a capital letter. - Hindol