memory trouble with doubly linked list in C

I’m trying to write a doubly linked list. The following code passes my tests, but I’m allocating memory for new nodes in both the next direction and the prev direction. Specifically, the problem is that I believe I shouldn’t have to allocate current in the push function because those nodes were already allocated in past iterations with new. However, if I set new->prev = current without allocating current I get a segmentation fault. Note that the code below functions properly as a singly linked list if I don’t allocate the current or use ->prev.

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

struct list{
    int value;
    struct list *next;
    struct list *prev;
};
struct list *head;
struct list *tail;

void init(val){
    head = (struct list *)malloc(sizeof(struct list *));
    head->value = val;
    head->next = NULL;
    head->prev = NULL;

    tail = malloc(sizeof(struct list *));
    tail->value = val;
    tail->next = NULL;
}

void push(int val){
     struct list *new;
     struct list *current;
     new = (struct list *)malloc(sizeof(struct list *)); //allocate memory space for next side
     current = (struct list *)malloc(sizeof(struct list *)); //allocate memory space for prev side
     new->value = val;
     new->next = NULL;
     current = head;
     while(current->next!=NULL){current = current->next;}
     new->prev = current;
     current->next = new;
     tail = new;
 }

 int main(){
     printf("init with 10\n");
     init(10);
     printf("pushing 11\n");
     push(11);
     printf("pushing 12\n");
     push(12);
     printf("pushing 13\n");
     push(13);
     printf("testing\n");
     printf("2-1 %d\n",head->next->prev->value);
     printf("3-1 %d\n",head->next->next->prev->value);
     printf("h4-1 %d\n",head->next->next->next->prev->value);
     printf("t-1 %d\n",tail->prev->value);
     printf("t-2 %d\n",tail->prev->prev->value);
     printf("t %d\n",tail->value);
 }


Download memory.trouble.with.doubly.linked.list.in.c.zip
Direct Link


Download


Download memory.trouble.with.doubly.linked.list.in.c.zip
Mediafire


Download


Download memory.trouble.with.doubly.linked.list.in.c.zip
FILESMONSTER


Download


Download memory.trouble.with.doubly.linked.list.in.c.zip
Uploadbaz


Download


Download memory.trouble.with.doubly.linked.list.in.c.zip
Firedrive


Download

Both comments and pings are currently closed.

Comments are closed.