Segmentation fault when adding a node to a linked list
-
12-12-2019 - |
Frage
typedef struct
{
uint32_t field_id;
uint16_t length;
}entry_t;
struct node
{
entry_t *sp_entry;
struct node *next;
}*head;
I have a function called add() to add entry to the linked list.
void add( entry_t *entry )
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->sp_entry = entry;
if (head== NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}
Please not that the "value" that is stored in the linked list node is itself a pointer to a structure.I am getting a segmentation fault at
temp->sp_entry = entry;
which is probably because I am not allocation memory for entry_t structure.What I want to know is that is this a usual use case? If yes how do I do it.Do I have to do
temp->sp_entry = malloc(sizeof (entry_t));
before making an assignment? Also is there a more elegant way to achieve this?
Additional information.
when I run gdb I get
p *temp
$3 = {sp_entry = 0x0, next = 0x3e64656269}
the sp_entry looks like it is a null pointer.This is printed after malloc in add() function.And also my code has been combined with "-g -O0 -Wall".There has been no warnings
Lösung
Your code looks okay. temp->sp_entry = entry;
should not segfault since you allocated temp
on the previous line.
Pointer errors can be insidious. The line that crashes isn't necessarily the line at fault. add()
looks correct, so I suspect there's an error earlier in your program's execution that doesn't cause your program to crash immediately.
When I run gdb I get:
p *temp $3 = {sp_entry = 0x0, next = 0x3e64656269}
The sp_entry looks like it is a null pointer.
Not a problem. You haven't initialized temp->sp_entry
or temp->next
yet so their values are meaningless.
What's important is temp
's value. It seems to be a valid pointer since gdb can print *temp
. This is really where the segfault is occurring? I would have expected gdb to complain about temp
being a pointer to an invalid memory location and refuse to print *temp
.
Andere Tipps
Not enough karma (?) to post a comment, so posting this as an answer...
If you are on a unixy system, run Valgrind (http://valgrind.org/) to see offending memory read/write(s)
The code seems fine. The only way it can give a segmentation fault is if malloc returned null or an invalid value. I would suggest checking the value returned by malloc for a null before attempting to use it.