I have been tasked with the project of creating a Linked List inside of a flat assembler for a class project. I need to be able to store words there dynamically. I understand vaguely memory allocation and de allocation. What I don't understand is what turns this allocation into a Linked List or how to create a Linked List inside of the flat assembler. I have looked at a lot of examples across the internet talking about nodes and memory segments, but I'm not sure how these actually get put together. I would greatly appreciate if someone could explain how I could actually create a Linked List in the flat assembler. Thanks in advance.
A (singly) linked list is composed of nodes that point to each other in order. You have a root node, which holds data and points to another node, which holds data and points to another node, and so on for all the data in the list.
Generally, you would want to create functions for interacting with the list. They will abstract away dealing with the list directly. Minimally, you would would a function to create, insert, remove, get, and delete (delete the entire list, that is).
You need to know the size of the pointer and the size of the data to know the size of the allocation you need to make a node. Since you're in 16bit, you need the segment (2 bytes) and the offset (2 bytes). A node for storing 2 bytes of data (a 16bit integer) could be laid out with the next pointer first and then the data. So the layout is base = segment, base + 2 = offset, base + 4 = data.
So to access the pointer to the next node, with the pointer to the current node in es:ax
, you would first get the first the next segment, then the offset.
mov fs, [es:ax]
add ax, 2
mov cx, [ds:ax]
; fs:cs points to next node in list
To get the data from that node, in fs:cx
, we would do add cx, 4
then mov dx, [fs:cx]
.
So now you now how to get data and get the next node. Those are the building blocks you need to traverse a linked list.
To allocate a new list, you would allocate the first node (6 bytes in the case of storing a 16bit integer), put 0 in its segment and offset and put the data in its data slot. So, say the node (the 6 bytes of memory you just allocated) is at fs:cs
. You would
mov [fs:cx], 0
add cx, 2 ; assuming cx doesn't overflow...
mov [fs:cx], 0
add cx, 2
mov [fs:cx], `data`
To add a new node, you would traverse the list (like explained above) until you found the end. The end being the node with 0 segment and offset. Then you would allocate 6 bytes for the new node. Store the pointer to the new node in the tail. And then store the data in the new node and make the new node's pointer 0 (like you did with the first node in the code above).