【问题标题】:segmentation error when accessing a linked list or doing a malloc() on linux访问链表或在 Linux 上执行 malloc() 时出现分段错误
【发布时间】:2012-02-17 21:00:33
【问题描述】:

我在 Linux 系统上遇到了分段错误问题。 我正在使用 Aho 和 Ullman 的“计算机科学基础”C 版中的代码。 这是代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct que_element
{
    long mem_address;
    long mem_data;

    int msg;
} Qq;

typedef struct CELL *LIST;
struct CELL
{

    Qq el;

    int element;
    LIST next;
};


Qq l1element;

typedef struct
{
    LIST front;
    LIST rear;
} QUEUE;

main()
{
    QUEUE *l1c2l1d; /*L1 Controller to L1 Data */

    l1c2l1d->front = malloc(sizeof *l1c2l1d);
}

【问题讨论】:

  • 如果要代表true/false,请使用typedef char BOOLEAN。 ;) int 通常在 32 位上有 4 个字节,而 char 总是有 1 个字节。
  • @Gandaro 但是 int 通常比 char 访问更快。
  • 为什么要定义自己的布尔值而不是包含stdbool.h

标签: c segmentation-fault malloc


【解决方案1】:

我缺少初始化步骤吗?

是的,l1c2l1d 在您的代码中未初始化。取消引用它意味着取消引用NULL(因为l1c2l1d 是全局的)。试试这个:

l1c2l1d = malloc(sizeof *l1c2l1d);
l1c2l1d->front...

根据上次编辑编辑

你有这个:

main()
{
    QUEUE *l1c2l1d; /*L1 Controller to L1 Data */

    l1c2l1d->front = malloc(sizeof *l1c2l1d);
}

在这种情况下,l1c2l1d 未初始化,它指向垃圾。试试这个(这次复制粘贴):

main()
{
    QUEUE *l1c2l1d; /*L1 Controller to L1 Data */

    l1c2l1d = malloc(sizeof *l1c2l1d);
    l1c2l1d->front = malloc(*l1c2l1d->front);
}

【讨论】:

  • 我刚试过 l1c2l1d = malloc(sizeof *l1c2l1d) ,但也导致分段错误。
  • 我只是尝试在main()中定义l1c2l1d,还是分段错误。
  • @Mark 一定是其他原因造成的(例如您的 enqueue 函数)。
  • 我删除了所有的函数定义(enque、deque 等)。我只有 main() 以及 QUEUE 和链接列表定义。它仍然死在第一行(malloc)。
  • 我认为是时候下注了。我将只使用一个结构数组作为我的链表。没那么花哨,但我不必担心 malloc()。感谢您的帮助。
【解决方案2】:

您似乎正在寻求以下方面的东西:

main()
{
    QUEUE l1c2l1d = { 0, 0 }; /*L1 Controller to L1 Data */

    l1c2l1d->front = l1c2l1d->rear = malloc(sizeof CELL);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多