简体   繁体   中英

C - Segmentation fault on function with pointers

I have a list of 6 elements of a struct type:

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.

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. _END is a global constant defined as it follows:

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)

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.

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. 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.

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.

Then assigned values to each of them in the next lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM