#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
5 Answers 5
head = NULL;
head -> item = 0;
*** segmentation fault, beacuse head is null, can't dereference
head -> next = NULL;
1 Comment
I would suggest using GDB, run gdb with this program. When it segfaults it'll give you a stack trace of exactly where the program seg faulted. you can then print relevant variables using the 'p command'. Seg fault always means accessing memory that is outside of your processes reach (pointers with values that aren't within your process - invalid pointers). Learning to use GDB well will save you a lot of time, it's an insta-fix for seg faults :-)
Comments
When creating an empty list, you just need to set head
to NULL. There's no need to set its item
or next
, because it's an empty list. You were dereferencing the NULL pointer, which is not allowed, and on most systems will result in a segmentation fault or similar error.
list::list()
{
head = NULL;
}
Comments
Are you really suprised that this code crashes?
head = NULL;
head -> item = 0;
head -> next = NULL;
You assign NULL to a pointer and immediately reference it.
Comments
head = NULL;
head -> item = 0;
head -> next = NULL;
can not possibly work. The ->
operator dereferences the pointer, which obviously is not possible if its value is set to NULL
. You need to allocate memory for the head beforehand:
head = new node;
delete
solve a segmentation fault? Also, did you try running your code in a debugger?list::list
you sethead = NULL
and then you try to dereference it. How do you expect that to work?