【问题标题】:Segmentation fault in C while creating linked list from array从数组创建链表时C中的分段错误
【发布时间】:2018-03-27 18:49:45
【问题描述】:

正如我在标题中所说,我正在尝试从 数组 生成一个链表P 是一个 结构,其中包含 float x 和一个指向列表中下一个元素的 指针gen_list 函数一被调用,第一行代码“first->x = V[0]”就返回了分段错误,这是我从调试器中得到的:

Program received signal SIGSEGV, Segmentation fault.                                                                 
0x00000000004007f6 in gen_list (V=0x602010, n=10000, first=0x601068 <first>)                                          
    at main.c:46                                                                                                     
46              (*first)->x = V[0];                                                                                   
(gdb)

我好像找不到问题,请帮忙!!

这里是重现错误所需的最少代码:

typedef struct Popis {
float x;
struct Popis *next;}P;
P *first;

int main(){
float v[10];
v[0] = 1;
first->x = v[0];
}

我的代码:

P* gen_list(float V[], int n, P *first) {
first->x = V[0];
P *T = NULL;
P *new = NULL;
T = first;

t1 = clock();
for (int i = 1; i < n; i++) {
    new->x = V[i];
    T->next = new;
    T = new;
}
T->next = NULL;
t2 = clock();
printf("\nTime for creation of linked list is: %dms", t2 - t1);
return first;}

【问题讨论】:

  • 该错误可能在您的代码中的其他地方。尝试通过valgrind 运行它。如果你踩到了你不应该踩到的内存,它会告诉你。
  • 如果您在调试器中,请使用它。打印firstV 的值。
  • 我添加了最小的。
  • 你需要了解对象和指针。并正确格式化您的代码。

标签: c function linked-list segmentation-fault


【解决方案1】:

当指针操作错误时通常会发生分段错误,例如在您的示例代码中:

typedef struct Popis {
  float x;
  struct Popis *next;
} P;
P *first;

int main(){
  float v[10];
  v[0] = 1;
  first->x = v[0];
}

看看变量 *first,它是一个指向 Popis 结构体的指针,现在在 ma​​in 函数中你尝试使用 *first 指针,但您需要分配内存空间才能使用它。如果使用以下代码在使用前分配内存,则不会出现分段错误错误。

first = (P*)malloc(sizeof(P));

【讨论】:

  • 谢谢,这就是问题所在,我现在已经为指针分配了内存,一切正常!
【解决方案2】:

这个问题很可能是由于分配的内存不足。在“需要最少的代码”代码 sn-p 中,没有为您的结构分配内存,这就是进程被终止的原因。内核返回 SIGSEGV 信号,因为您尝试在程序尚未分配(请求)的内存上进行写入。为了解决这个问题,你可以简单地使用malloc();分配内存,希望下面的代码可以帮助你解决这个问题:

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

typedef struct Popis {
    float x;
    struct Popis *next;
}P;

int main(){

    P *first;
    /*Here we actually create the structure in the memory - we allocate memory for it*/
    first = (struct Popis*)malloc(sizeof(struct Popis));
    /*This is a simple check if the memory allocation was sucessfull*/
    if(!first) 
    {
        fprintf(stderr, "Error has occured during the memory allocation!\n");
        exit(1);
    }

    float v[10];
    v[0] = 1;
    first->x = v[0];
    printf("%f", first->x);

    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多