Search code examples
clinked-listdynamic-memory-allocationundefined-behaviorsingly-linked-list

How to fix setting ending node in a linked list created by malloc causes a segmentation fault?


I am learning dynamic memory management and am working on a program that lets you set the size of the array, and then generates it, and prints it out.

here is the code:

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

typedef struct node{
    int number;
    struct node *next;
}node;

int main(void)
{
    node *ptr;
    int n, i;
    printf("How big should the array initially be? ");
    //scanf("%i",&n);
    printf("\n\n");

    // for debugging purposes
    n = 8;
    
    
    ptr = (node *)malloc(n * sizeof(node));
    
    for (i = 0; i < n; i++)
    {
        ptr[i] = (struct node)
        {
            .number = i + 1,
            .next = &ptr[i + 1]
        };

        
    }
    struct node *listptr = &ptr[0];

    ptr[n - 1].next = NULL;
    /*while (listptr->next != NULL)
    {
        
        printf("ptr[%i].number = %i, ptr[%i].next->number = %i"
        ,i,ptr[i].number,i,ptr[i].next->number);
        listptr = listptr->next;
        i++;
    }*/

    for (i = 0; i < n; i++)
    {
        printf("ptr[%i].number = %i, ptr[%i].next->number = %i\n"
        ,i,ptr[i].number,i,ptr[i].next->number);
    }
    printf("How much bigger would you like this array to be? ");
    printf("\n\n");
    
    

    free(ptr);
}

I have tried changing malloc to calloc but I still get the same error. How do I set the ending node.next to NULL and terminate the program? when I run the code I get this output:

How big should the array initially be? 

ptr[0].number = 1, ptr[0].next->number = 2
ptr[1].number = 2, ptr[1].next->number = 3
ptr[2].number = 3, ptr[2].next->number = 4
ptr[3].number = 4, ptr[3].next->number = 5
ptr[4].number = 5, ptr[4].next->number = 6
ptr[5].number = 6, ptr[5].next->number = 7
ptr[6].number = 7, ptr[6].next->number = 8
zsh: segmentation fault ./file

Solution

  • In this for loop

    for (i = 0; i < n; i++)
    {
        printf("ptr[%i].number = %i, ptr[%i].next->number = %i\n"
        ,i,ptr[i].number,i,ptr[i].next->number);
    }
    

    when i is equal tp n - 1 this expression ptr[i].next->number tries to access memory using the null pointer ptr[i].next.

    Also in this for loop

    for (i = 0; i < n; i++)
    {
        ptr[i] = (struct node)
        {
            .number = i + 1,
            .next = &ptr[i + 1]
        };
    
        
    }
    

    you have to write

    for (i = 0; i < n; i++)
    {
        ptr[i] = (struct node)
        {
            .number = i + 1,
            .next = i == n - 1 ? NULL : &ptr[i + 1]
        };
    
        
    }