Search code examples
assemblymasm

Confused about pointers and values in Assembly


I'm using the MASM Assembler. Let's look at this short code (from a book I've been reading):

    .data
var1 BYTE 10h

.code
main proc
    mov esi,OFFSET byteVal
    mov al,[esi] ; AL = 10h

I didn't exactly understand how byteVal is translated to machine code - I know it's an identifier, a symbolic name. As I understand, at runtime byteVal is the memory address of the value 10h, right? but the book says that these two instructions are the same:

mov al var1
mov al,[var1]

I don't understand why they do the same.


var1 = the address of 10h

[var1] = 10h


Isn't this true? the book said that square brackets "dereference" the variable, yet it said that these two are the same.

and if var1 is the location in memory, what's the difference between it and using OFFSET var1 then ? I mean, offset is the location in memory, isn't it? and the book said: "The OFFSET operator returns the distance of a variable from the beginning of its enclosing segment." Why then the first variable's offset isn't zero, since it's the first variable in the segment? I just CANT figure it out. Probably I should switch a book...


Solution

  • In MASM (and only there!) mov al, var1 works with the content of var1. Using the name of the label "naked" is called "Direct Memory Operand". See MS MASM 6.0 Programmer’s Guide (Scroll to section 3.2.3, "Direct Memory Operands"). If you need the address of that label you have to use the OFFSET-Operator.

    The operator [] has a special meaning. I adds the expression between the brackets to the expression before the brackets.

    mov al, [var1]

    is equivalent to

    mov al, 0[var1]

    is equivalent to

    mov al, 0 + var1

    is equivalent to

    mov al, var1 + 0

    is equivalent to

    mov al, var1

    You shouldn't use the []-operator in MASM, if you don't really need it, since it has some side effects.