1
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”结合使用。没有任何警告

4

3 回答 3

2

你的代码看起来不错。temp->sp_entry = entry;不应出现段错误,因为您temp已在上一行分配。

指针错误可能很隐蔽。崩溃的线路不一定是故障线路。add()看起来是正确的,所以我怀疑在您的程序执行的早期有一个错误不会导致您的程序立即崩溃。

当我运行 gdb 时,我得到:

p *temp
$3 = {sp_entry = 0x0, next = 0x3e64656269}      

sp_entry 看起来像是一个空指针。

不是问题。您尚未初始化temp->sp_entrytemp->next尚未初始化,因此它们的值毫无意义。

重要的是temp的价值。它似乎是一个有效的指针,因为 gdb 可以打印*temp。这真的是发生段错误的地方吗?我本来希望 gdb 抱怨temp是指向无效内存位置的指针并拒绝打印*temp

于 2012-10-02T01:56:07.150 回答
2

没有足够的业力(?)发表评论,所以发布这个作为答案......

如果您使用的是 unixy 系统,请运行 Valgrind (http://valgrind.org/) 以查看有问题的内存读/写

于 2012-10-02T02:14:51.917 回答
1

代码看起来不错。它可以给出分段错误的唯一方法是 malloc 返回 null 或无效值。我建议在尝试使用它之前检查 malloc 返回的值是否为空。

于 2012-10-02T04:04:25.280 回答