在分配链表并在c中为其赋值时出现分段错误

Getting segmentation fault when allocating a linked list and assigning it values in c

我正在尝试创建一个单链表并用第一个给定的 n integers.But 初始化它,每当我 运行 it.This 是我的代码时我都会遇到分段错误。

 typedef struct floatList{float fval;struct floatList * fnext;}node_f;


 node_f* FL_firstInts(int n){

        node_f *res=(node_f*)malloc(sizeof(node_f));
        res=res->fnext;

        for(int i=1;i<=n;i++){
            res->fval=i;
            res=res->fnext;
        }
        return res;
    }

void FL_show(struct floatList *list, char *label){
    int i=0;
    while(list->fnext!=NULL){
        printf("%d: %f\n",i,f->fval);           
        list=list->fnext;
        i++;
    }
}

为了在主函数中进行测试,我写了下面的内容

node_f *ten = FL_firstInts(10);
FL_show(ten,"10 first integers");

但是当我 运行 程序时,出现分段错误,我该如何解决?

node_f *res=(node_f*)malloc(sizeof(node_f));
res=res->fnext;

崩溃的原因是您从未初始化 res->fnext 指针。
所以在访问它之前将它设置为列表中的实际下一个元素。

总的来说你的代码有点模糊。
您正在为 one node_f 分配内存,但您实际上是在尝试将 n 元素放入其中。

要为 n 个元素分配内存,只需将一个元素的大小乘以 n

node_f *res= (node_f*) malloc(sizeof(node_f) * n);

然后初始化fnext指针。

for(size_t index{0}; index < n - 1; index++)
  res[index].fnext = &res[index + 1];
res[n - 1].fnext = nullptr;

在函数 FL_firstInts 中,您分配了 node_f

类型的未初始化对象
node_f *res=(node_f*)malloc(sizeof(node_f));

所以下面的语句

res=res->fnext;

已经调用了未定义的行为。

函数至少可以这样定义

node_f * FL_firstInts( int n )
{
    node_f *head = NULL;
    node_f **current = &head;
`
    for ( int i = 0; i < n; i++ )
    {
        *current = malloc( sizeof( node_f ) );

        ( *current )->fval  = i;
        ( *current )->fnext = NULL;

        current = &( *current )->fnext;
    }

    return head;
}

函数FL_show有同样的错误,而且参数label没有被使用。

函数可以这样定义

void FL_show( const node_f *head, const char *label )
{
    if ( label ) puts( label );

    for ( int i = 0; list != NULL; list = list->fnext )
    {
        printf( "%d: %f\n", i, f->fval );           
        i++;
    }
}