Learning Assembly changed my view about the world of programming. This enabled me to understand how a computer works easily.
My main advance was regarding memory management. Personally, I had a lot of issues learning about pointers, it just didn’t make sense. But when learning assembly, it was like a snap to understand how they work.
Assembly isn’t really easy or viable for creating large projects, it’s quite simple, since everything is broken down into small instructions.
So, let’s see in details how Assembly helped me to be a better Software Engineer.
We in this field often hear about Heap and Stack. But isn’t it all RAM?
The fact is that the Heap doesn’t exist, it’s an abstraction of the Operational System. In return, the Stack does exist, and can be directly accessed using assembly.
First, let me explain the difference between these two data structures.
Stack
The Stack is much faster than the heap and operates in a last-in-first-out (LIFO) manner. It grows downwards in memory, meaning that the first item placed on the stack resides at the highest memory address.
The Stack is primarily used in function calls. When a function is invoked, the state of all relevant registers are saved to the Stack, and then the function is executed. When the function execution ends, the saved state of the registers are popped back into them, restoring the original state of the program.
In assembly (at least the x86–64), we use two instructions to manage the stack, PUSH and POP. Here’s how to use it:
global _startsection .text
_start:
mov eax, 2 ; Put the decimal "2" in eax
push eax ; Push the value of eax into the stack
mov eax, 78 ; Overwrite eax with new value
pop eax ; Pop the last value of the stack into eax
; Eax value is 2 again
It’s possible to do it without using them, but they we’re created for convenience.
What these instructions do is:
; PUSH
sub rsp, 8 ; Moves the Stack pointer down by 8 bytes (64 bits)
mov [rsp], eax ; Moves the value of EAX to the address of the RSP; POP
mov eax, [rsp] ; Moves the value pointed by the address of RSP into EAX
add rsp, 8 ; Moves the Stack pointer up by 8 bytes (64 bits)
Here, RSP (Register Stack Pointer) keeps track of the top of the stack. Specifically, it points to the address of the most recently pushed value.
An important point to note: popping a value doesn’t actually remove it from memory. Inste