【问题标题】:Segmentation fault when adding a node to a linked list将节点添加到链表时出现分段错误
【发布时间】: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


【解决方案1】:

您的代码看起来不错。 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

【讨论】:

  • 当我运行 gdb 时我得到 p *temp $3 = {sp_entry = 0x0, next = 0x3e64656269}
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-28
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多