On Friday, 3 April 2015 at 22:06:06 UTC, Namespace wrote:
On Friday, 3 April 2015 at 22:02:13 UTC, Kitt wrote:
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?

Why did you allocate only 2 / 10 bytes and not Node.sizeof bytes? Since your Node struct has at least one pointer (nexT) and a value (I assume of type int) you must allocate at least 8 bytes for one Node. I'm sure that is at least one of your problems.

Wow, I can't even begin to explain how red my cheeks are right now. You're completely right; I have no idea what my head was thinking. Sure enough, call malloc with the correct type, and the error goes away =P

Thanks for the help =) I guess I've been in C# land at work for way too long now, my low level C skills are evaporating!

Reply via email to