Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

assembly - Why in NASM do we have to use square brackets ([ ]) to MOV to memory location?

For example if I have a variable named test declared like:

test db 0x01      ;suppose the address is 0x00000052

If I do something like:

mov rax, test     ;rax = 0x00000052
mov rax, [test]   ;rax = 0x01

But, when I try to save in it, if we're following the same pattern:

mov test, 0x01    ;address 0x00000052 = 0x01
mov [test], 0x01  ;address 0x01 = 0x01

But it actually is:

mov [test], 0x01  ;address 0x00000052 = 0x01

So, why the square brackets behave differently depending if they are the first or second operands?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In most assemblers, using square brackets dereferences a memory location. You are treating the value as a memory address.

For example, let's take this for an example.

mov ax, [0x1000]

This will get the value at 0x1000 and put it into AX. If you remove the square brackets, you only move 0x1000.

If you move a value to a number, you are putting it into the value (memory location).

If you are a C developer, here's an example problem.

Don't let this example annoy you if you've been bullied into learning C by others, calling you a 'troll'.

You can ignore this if you want but you might have known about scanf() if you know C.

int a = 10;
scanf("%d", a);

Now, this is a very common mistake because we are not getting the memory address of the variable. Instead, we are using its value as the address. The scanf() function requires you to give the the address.

If we did this,

scanf("%d", &a);

we would have the address of the variable a.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...