0

DoubleLinkedList.h

#ifndef _DOUBLE_LINKED_LIST_H
#define _DOUBLE_LINKED_LIST_H

typedef unsigned int uint;
typedef unsigned long ulong;
typedef void* Object;   
typedef struct _DNode {
    Object data;
    struct _DNode* prev;
    struct _DNode* next;
}DNode;

typedef struct _DoubleLinkedList{
    DNode* head;
    DNode* tail;
    uint length;
    uint elementSize;
}DoubleLinkedList;

DoubleLinkedList* allocDList (uint elementSize);
#endif

DoubleLinkedList.c

#include "DoubleLinkedList.h"

DoubleLinkedList* allocDList (uint elementSize)
{
    DoubleLinkedList* l;
    l->head = NULL;
    l->tail = NULL;
    l->length = 0;
    l->elementSize = elementSize;
    return l;
}

main.c

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

int main ()
{
    DoubleLinkedList* ab;
    ab = allocDList(10);
    return 0;
}

When I try to run this I get a segmentation fault with a core dump.

this is what is required in the assignment.

DoubleLinkedList* allocDList(uint elementSize): this function allocates the DoubleLinkList

  • 5
    in `allocDList`, `l` is uninitialised. You'll want to allocate some memory for the new node. – M Oehm Jun 19 '14 at 17:49

3 Answers3

2

You haven't initialised l, so l->HEADwon't work. You can initialise it using malloc as:

DoubleLinkedList* l = malloc(sizeof(DoubleLinkedList));

Also, in the main function, once you are done using the variable ab, remember to release the memory used by it using the free function as follows:

int main ()
{
 DoubleLinkedList* ab;
 ab = allocDList(10);

 //Processing here

 free(ab); //Release once it is no longer needed

 return 0;
}
shree.pat18
  • 21,449
  • 3
  • 43
  • 63
1

Update DoubleLinkedList.c as:

DoubleLinkedList* allocDList (uint elementSize)
{
    DoubleLinkedList* l;
    l = malloc(sizeof(DoubleLinkedList));
    l->head = NULL;
    l->tail = NULL;
    l->length = 0;
    l->elementSize = elementSize;
    return l;
}
j809
  • 1,499
  • 1
  • 12
  • 22
1

DoubleLinkedList* l;

You need to allocate some memory to l

l = (DoubleLinkedList*) malloc(sizeof(DoubleLinkedList));
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31