c - 返回结构时出现段错误

标签 c struct segmentation-fault

好吧,对于一个作业,我必须创建一个队列 ADT,但我的代码从一开始就失败了。

每个测试的第一个方法调用是 que_create,这就是段错误。方法如下:

QueueADT que_create(int (*cmp)(const void *a, const void *b)) {
    QueueADT queue = {0, 0, 1, 10, 0, calloc(10, sizeof(void *)), cmp};
    return queue;
}

结构:

typedef que_adt {
    unsigned int head;
    unsigned int rear;
    unsigned int empty;
    unsigned int capacity;
    unsigned int nitems;
    void **array;
    int (*cmp)(const void *a, const void *b);
} QueueADT;

包含行上的方法段错误 返回队列;

GDB: 队列初始化和返回行上的断点。 之前

queue = {head = 0, rear = 0, empty = 0, capacity = 0, nitems = 0, array = 0xff0000000000000000, cmp = 0x1}

之后

queue = {head = 0, rear = 0, empty = 1, capacity = 10, nitems = 0, array = 0x603010, cmp = 0x7ffffffffe938}

瓦尔格林德: 一个错误:进程因信号 11 (SIGSEGV) 的默认操作而终止 que_create (queueADT.c:34) 处地址 0x400796 处映射区域的权限错误//<- 方法返回行

我尝试寻找这个问题的答案,因为我很困惑,但所有关于这类事情的问题都不像我的那么简单。我实际上是在初始化一个结构并返回它。我尝试注释掉初始化中的 calloc 以及 cmp 函数,但同样的错误仍然存​​在。有什么建议么?

最佳答案

此代码有效:

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

 typedef struct que_adt {
     unsigned int head;
     unsigned int rear;
     unsigned int empty;
     unsigned int capacity;
     unsigned int nitems;
     void **array;
     int (*cmp)(const void *a, const void *b);
 } QueueADT;

 int
 compare( const void *a, const void *b)
 {
    return 1;
 }

 QueueADT que_create(int (*cmp)(const void *a, const void *b)) {
     QueueADT queue = {0, 0, 1, 10, 0, calloc(10, sizeof(void *)), cmp};
     return queue;
 }

 int
 main(void)
 {
      QueueADT q = que_create( compare );

      return 0;
 }

在 gdb 中,我输入“p q”,得到了

 (gdb) p q
 $1 = {head = 0, rear = 0, empty = 1, capacity = 10, nitems = 0, array = 0x602010, cmp = 0x40052d <compare>}

你的代码和这个没有太大区别。我复制并粘贴了它。唯一的区别是我必须定义一个虚拟的 Compare() 函数。

关于c - 返回结构时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43428973/

相关文章:

c++ - 错误 : dereferencing pointer to incomplete type

c - 使用 GNU 缩进命令应用仅包含制表符的 K&R 样式

链接器可以内联函数吗?

c - 程序在 t->time = t0 行崩溃;

c - 搜索并打印输入文件中所有不重复的结构名称

c - 为什么我们不能对新创建的结构体指针使用点

c - 在双指针上使用 strcpy 时出现段错误

c - 我想知道如何在unix中正确使用read()和open()函数

android - 需要帮助进一步调试 SEGV 问题 - Android NDK

c# - xamarin应用程序SIGSEGV错误