Is there a way to dereference a pointer stored in memory?

121 views Asked by At

I'm trying to store a pointer in a variable located on memory. How could I dereference it? I'm trying to do it like this:

pointer: db 0 ; the pointer variable
var: db 44 ; the normal variable
dereferenced: db 0 ; the result of dereferencing the value on `pointer`
start:
  mov al, var ; move `var`'s address to `al` register
  mov [pointer], al ; storing the previously moved `var`'s address on `pointer`
  ; dereferencing should go here

PS: I'm using nasm on Linux

I've already tried [[pointer]] but it gives me an error.

PPS: The error is only when trying to dereference.

1

There are 1 answers

5
Martin Rosenau On
pointer: db 0 ; the pointer variable

db is one byte, this means: 8 bits.

You are running a program on an x86. This means that a "normal" pointer is at least 16 bits (if you are running in 16-bit mode) in size.

I've already tried [[pointer]] but it gives me an error.

In assembly language, one instruction corresponds to one instruction that can be executed by the CPU.

In 1959, IBM built a computer that could dereference multiple levels of pointers (you would write this as [[[pointer]]]) in one single instruction. However, most modern computers are not able to do this. This is also true for x86-based computers. Such CPUs require multiple instructions to dereference a multi-level pointer:

First, they load the pointer into a register in one instruction; then they use the address in the register in the second instruction.

Example (x86, 32-bit):

mov eax, [pointer]
mov ebx, [eax]

And because one assembly instruction normally corresponds to exactly one CPU instruction, you also need to do this in assembly language.