Issue with free() for linked list implementation

Kitt via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 3 15:02:11 PDT 2015


Hello. I’m trying to write my own version of a list that doesn’t 
rely on the garbage collector. I’m working on a very bare bones 
implementation using malloc and free, but I’m running into an 
exception when I attempt to call free. Here is a very minimal 
code sample to illustrate the issue:

// Some constant values we can use
static const int two = 2, ten = 10;

// Get memory for two new nodes
Node* head = cast(Node*)malloc(two.sizeof);
Node* node1 = cast(Node*)malloc(ten.sizeof);

// Initialize the nodes
node1.value = ten;
node1.next = null;
head.value = two;	
head.next = node1;

// Attempt to free the head node
Node* temp = head.next;
head.next = null;
free(head); // Exception right here
head = temp;

Note, if I comment out the line ‘head.next = node1’, this code 
works. Does anyone know what I’m doing wrong with my manual 
memory management?


More information about the Digitalmars-d-learn mailing list