Search code examples
csegmentation-faultmallocstrcpy

Segmentation fault on strcpy even though I am using malloc


I am trying to make a Doubly Linked List in C.

And I get a Segmentation Fault even though I use malloc.

Here is my code so far.

list.h

#ifndef _LIST_
#define _LIST_

typedef struct listnode
{
    char * data;
    struct listnode * next;
    struct listnode * prev;
}listnode;

typedef struct list
{
    listnode * firstnode; // it will point to the first element in the list
    int size; // the size of the list
}list;

list create_list();
void insert_first_element(char *, list);

#endif

list.c

#include "list.h"
#include <stdlib.h>
#include <string.h>

list create_list()
{
    list L;
    L.firstnode= NULL;
    L.size = 0;

    return L;
}

void incert_first_element(char * d, list L)
{
    listnode * N= (listnode *)malloc(sizeof(listnode));
    
    strcpy(N->data, d); // <-- I get Segmentation Fault Here

    if(L.firstnode != NULL)
    {
        N->next=L.firstnode;
        N->prev=L.firstnode->prev;
        L.firstnode->prev=N;
        L.firstnode=N;
    }
    else
    {
        N->next=NULL;
        N->prev=N;
        L.firstnode=N;
    }
    L.size++;
    return 0;
}

main.c

#include <stdio.h>
#include "list.h"

int main(void)
{
   list L = create_list();
   incert_first_element("test",L);
  
   return 0;
}

Any idea what is causing the Segmentation Fault?

Because any problems I found when googling were caused by the lack of malloc, but here I do implement it.


Solution

  • this code

    listnode * N= (listnode *)malloc(sizeof(listnode));
    
    strcpy(N->data, d); // <-- I get Segmentation Fault Here
    

    allocates a listnode structure but the data field is a pointer on a char, so it's not initialized by the malloc call.

    The second line should be replaced for instance by a strdup call

    N->data = strdup(d);
    

    deallocation should also be done in 2 passes. First free(N->data) then free(N)