[英]Getting segmentation fault when allocating a linked list and assigning it values in c
I am trying to create a singly linked list and initialize it with the first given n integers.But i am getting segmentation fault whenever i run it.This is my code.我正在尝试创建一个单向链表并使用第一个给定的 n 个整数对其进行初始化。但是每当我运行它时我都会遇到分段错误。这是我的代码。
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++;
}
}
And in order to test in the main function, i write the following为了在主 function 中进行测试,我写了以下内容
node_f *ten = FL_firstInts(10);
FL_show(ten,"10 first integers");
But as i run the program, i get segmentation fault,how do i fix it?但是当我运行程序时,出现分段错误,我该如何解决?
node_f *res=(node_f*)malloc(sizeof(node_f));
res=res->fnext;
The reason for your crash is that you're never initialising the res->fnext
pointer.崩溃的原因是您从未初始化
res->fnext
指针。
So before accessing it set it to the actual next element in your list.所以在访问它之前将它设置为列表中的实际下一个元素。
In general your code is a bit fuzzy.一般来说,您的代码有点模糊。
You're allocating memory for one node_f
, but you're actually trying to put n
elements into it.您正在为一个
node_f
分配 memory ,但您实际上是在尝试将n
元素放入其中。
To allocate memory for the n
elements just multiply the size of one element by n
.要为
n
元素分配 memory,只需将一个元素的大小乘以n
即可。
node_f *res= (node_f*) malloc(sizeof(node_f) * n);
Afterwards initialise the fnext
pointers.然后初始化
fnext
指针。
for(size_t index{0}; index < n - 1; index++)
res[index].fnext = &res[index + 1];
res[n - 1].fnext = nullptr;
In the function FL_firstInts
you allocated uninitialized object of the type node_f在 function
FL_firstInts
中,您分配了类型为 node_f 的未初始化 object
node_f *res=(node_f*)malloc(sizeof(node_f));
So the following statement所以下面的语句
res=res->fnext;
already invokes undefined behavior.已经调用未定义的行为。
The function can be defined at least the following way至少可以通过以下方式定义 function
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;
}
Th function FL_show
has the same bug and moreover the parameter label
is not used. Th function
FL_show
有同样的错误,而且没有使用参数label
。
The function can be defined like function 可以这样定义
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++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.