[英]C - Segmentation fault on function with pointers
I have a list of 6 elements of a struct type:我有一个结构类型的 6 个元素的列表:
struct entry
{
int value;
struct entry *next;
};
I'm trying to create a function to initialize these six elements by assigning a random int to each value member.我正在尝试通过为每个值成员分配一个随机 int 来创建一个函数来初始化这六个元素。
void initializeList(struct entry *l_p)
{
while(l_p!=_END)
{
l_p->value=rand()%999;
l_p=l_p->next;
}
}
When this function is called in the main, *l_p
points at the very first element of the list.在 main 中调用此函数时, *l_p
指向列表的第一个元素。 _END
is a global constant defined as it follows: _END
是一个全局常量,定义如下:
struct entry const *_END=(struct entry *)0;
Now, every time I run my code I get this:现在,每次我运行我的代码时,我都会得到这个:
Segmentation fault (core dumped)分段错误(核心转储)
Process returned 139 (0x8B)进程返回 139 (0x8B)
I know this means I'm trying to access a part of memory I'm not allowed to, but I can't figure out how to fix my code.我知道这意味着我正在尝试访问我不允许访问的一部分内存,但我不知道如何修复我的代码。 Also, I'm pretty sure that the problem is caused by initializeList
because if I remove it and manually initialize every element of the list, the program runs smoothly.另外,我很确定问题是由initializeList
引起的,因为如果我删除它并手动初始化列表的每个元素,程序运行顺利。
Sorry everybody, my fault.对不起大家,我的错。 I've been trying to figure it out for so long and now, after a 5 minutes break, I can see that since my list wasn't initialized and the elements weren't linked to each other, I couldn't run a sequential scan over it.我一直试图弄清楚很长时间,现在,经过 5 分钟的休息,我可以看到由于我的列表没有初始化并且元素没有相互链接,我无法运行顺序扫描它。 Again, my fault, i'm still a noob, got plenty to learn :)再说一次,我的错,我还是个菜鸟,有很多东西要学:)
Actually there's an error in this:其实这里有一个错误:
l_p->value=rand()%999;
l_p=l_p->next;
You haven't allocated memory for l_p & then tried to assign a value in a restricted area leading to a Segmentation fault.您尚未为 l_p 分配内存,然后尝试在导致分段错误的受限区域中分配值。
You may try this你可以试试这个
void initializeList(struct entry *l_p)
{
l_p=(struct entry *)malloc(sizeof(struct entry));
l_p->next=NULL;
struct entry *pointer,* back=l_p;
for(int i=0;i<5;i++)
{
pointer=(struct entry *)malloc(sizeof(struct entry));
pointer->next=NULL;
back->next=pointer;
}
for(int i=0;i<6;i++)
{
l_p->value=rand()%999;
l_p=l_p->next;
}
}
I've created 6 nodes and connected them in the first 9 lines.我创建了 6 个节点,并在前 9 行中将它们连接起来。
Then assigned values to each of them in the next lines.然后在下一行中为它们中的每一个赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.