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
headto NULL? If not, your declaration ofheadafter yourstructdefinition leavesheaduninitialized, and yourhead == NULLtest will failstruct node*before mallocgcc -Wall)?