#include<iostream>
using namespace std;
class list
{
public:
list();
bool insertHead(int n);
private:
struct node
{
int item;
node *next;
};
node* head;
};
list::list()
{
head = NULL;
head -> item = 0;
head -> next = NULL;
}
bool list::insertHead(int n)
{
node* tempptr = new node;
tempptr->item = n;
tempptr->next = head;
head = tempptr;
return true;
}
int main()
{
list test1;
test1.insertHead(4);
return 0;
}
This code compiles fine but unfortunately segfaults when running. I tried adding delete tempptr at the end of the insertHead function but to no avail. I am so bad at memory allocation, I know a segmentation fault has to do with memory allocation during runtime. Can anybody help me? I'm just using insertHead to insert a integer into the front of a linked list. Can anybody help me out? Thanks! I combined the implementation and other files together so its easier to read...I think. Thanks
deletesolve a segmentation fault? Also, did you try running your code in a debugger?list::listyou sethead = NULLand then you try to dereference it. How do you expect that to work?