typedef struct
{
uint32_t field_id;
uint16_t length;
}entry_t;
struct node
{
entry_t *sp_entry;
struct node *next;
}*head;
我有一個名爲add()的函數將條目添加到鏈接列表。將節點添加到鏈接列表時出現分段錯誤
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;
}
}
請不就是「價值」存儲在鏈表節點本身就是一個指向structure.I我得到一個分段錯誤在
temp->sp_entry = entry;
這可能是因爲我沒有爲entry_t結構分配內存。我想知道的是這是一個常用的用例嗎?如果是,我該怎麼做。我必須做什麼
temp->sp_entry = malloc(sizeof (entry_t));
在做任務之前?還有更好的方法來實現這一目標嗎?
其他信息。
當我運行GDB我得到
p *temp
$3 = {sp_entry = 0x0, next = 0x3e64656269}
的sp_entry看起來是空pointer.This在加的malloc後打印()function.And也是我的代碼已經與「-g相結合 - O0-Wall「。一直沒有警告
你是否將'head'初始化爲NULL?如果沒有,你的'struct'定義之後的'head'聲明會使'head'未初始化,並且'head == NULL'測試將失敗 – pb2q
是的。我將頭初始化爲NULL。 – liv2hak
嘗試在malloc之前刪除cast到'struct node *' –