【发布时间】:2012-09-22 21:43:17
【问题描述】:
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;
}
}
请注意,存储在链表节点中的“值”本身就是一个指向结构的指针。我遇到了分段错误
temp->sp_entry = entry;
这可能是因为我没有为 entry_t 结构分配内存。我想知道这是一个常见的用例吗?如果是,我该怎么做。我必须这样做吗
temp->sp_entry = malloc(sizeof (entry_t));
在分配任务之前?还有没有更优雅的方法来实现这一点?
附加信息。
当我运行 gdb 时,我得到了
p *temp
$3 = {sp_entry = 0x0, next = 0x3e64656269}
sp_entry 看起来像是一个空指针。这是在 add() 函数中的 malloc 之后打印的。而且我的代码已与“-g -O0 -Wall”结合使用。没有任何警告
【问题讨论】:
-
您是否曾经将
head初始化为NULL?如果没有,您在struct定义之后对head的声明使head未初始化,并且您的head == NULL测试将失败 -
是的。我确实将 head 初始化为 NULL。
-
尝试在 malloc 之前将演员表移除到
struct node* -
您的程序编译时是否没有警告,是否启用了警告(例如
gcc -Wall)?
标签: c pointers linked-list segmentation-fault singly-linked-list