【问题标题】:Pointers in C - finding segmentation fault issuesC 中的指针 - 查找分段错误问题
【发布时间】:2020-07-04 06:39:36
【问题描述】:

我在使用和设置链接列表中的指针时遇到了一些麻烦......我的代码中不断出现分段错误,有人在这里看到任何明显的问题吗?

最近,我在编写的每一段代码中都遇到了段错误,这非常令人沮丧,因为我发现它们几乎无法追踪。我是一名物理专业的学生,​​试图自学如何编码,所以我是一个非常新手程序员,我很抱歉我问了这么一个常见的问题,非常感谢任何建议!

(为了解释代码,我们应该创建一个包含三个随机变量的节点的链表,然后以三种不同的方式对列表进行排序,rand_double 只是生成一个随机双精度并且运行得很好,所以我知道问题是不在那里!!)

Node* randomList(int length){

int i;
Node **head, *new;

head = malloc(sizeof(Node**));
*head = NULL;

new = malloc(sizeof(Node*));
new = NULL;


/*create list by adding new node to beginning of list, using 'push' method*/
for(i=0;i<length; i++){

    /*set data in new node*/
    new->value = (int)rand_double(0,10);
    new->key1 = rand_double(10.0, 50.0);
    new->key2 = rand_double(50.0, 90.0);

    new->sort1 = malloc(sizeof(Node*));
    new->sort2 = malloc(sizeof(Node*));
    new->next = malloc(sizeof(Node*));

    new->sort1 = NULL;
    new->sort2 = NULL;

    /*
        set pointers
        new node points to what head points to, head points to new
    */  
    new->next = *head;
    *head = new;
}


return *head;

}

【问题讨论】:

  • 您将 new 分配给 NULL(这是泄漏内存),然后在分配 new->value 时尝试取消引用指针。
  • 提示:检查尺寸 -->> new-&gt;sort1 = malloc(sizeof(Node*));

标签: c pointers struct linked-list segmentation-fault


【解决方案1】:

您的代码中有几个问题:

-你正在 malloc-ing sizeof(Node**) 或 (Node*)- 这不是你想要的,你需要为 sizeof(Node) 分配空间。

-你不应该为head分配空间,它只会指向第一个节点

-你有几个内存泄漏,你调用 malloc 然后重新分配变量

-你只为 new 分配空间一次。您需要在 for 循环中移动 new=malloc 行

-sort1 和 sort2 被赋值但从未使用过

如果您仍然遇到问题,请解决这些问题并更新问题。祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2023-04-04
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 2013-09-18
    • 2016-02-24
    相关资源
    最近更新 更多