Chuckles
Chuckles

Reputation: 3

Design choices implementing linked list in C

I hope this question isn't too open for the format of this site. I am somewhat new to C, and enjoy playing around with it to learn its intricacies. My current "task" is building a singly-linked list.

Here's my setup: The first iteration of my linked list program stored all nodes in one contiguous block of memory. This required realloc for my push and pop functions.

However, when I got to using realloc, I decided to try a new design where malloc and free is called during the creation or deletion of a single node, respectively. I've read that on larger scales this can be very hampering to the program.

Which way is better, the first or the second? Or do both ideas lend themselves to certain implementations? Forgive me if this is too broad, I just want to check my understanding and really learn about designing a program.

Upvotes: 0

Views: 80

Answers (1)

pm100
pm100

Reputation: 50190

Your second way is the 'classic' linked list. malloc each node in turn. Each node has a pointer to the next node. Last one has a null next pointer. You have a root pointer that points to the first node

There is no scale issue with this; modern heap managers are very efficient. There is however a brain scale issue. You need to write nice clean code so that you dont leak or crash :-)

if you are doing this on linux learn how to use a tool called valgrind. (and of course learn how to use gdb)

Upvotes: 2

Related Questions