Dennis
Dennis

Reputation: 1065

How does a variable definition work in assembly?

The popular hello world program in assembly defines within the .data section the string "Hello, world!". According to this tutorial (http://www.tutorialspoint.com/assembly_programming/assembly_variables.htm) db defines one byte (allocate one byte in memory).

    section .text
    global _start   ;must be declared for linker (ld)
_start:             ;tells linker entry point
    mov edx,len     ;message length
    mov ecx,msg     ;message to write
    mov ebx,1       ;file descriptor (stdout)
    mov eax,4       ;system call number (sys_write)
    int 0x80        ;call kernel

    mov eax,1       ;system call number (sys_exit)
    int 0x80        ;call kernel

section .data
msg db 'Hello, world!', 0xa  ;our dear string
len equ $ - msg     ;length of our dear string

Does this mean one byte will be allocated for each character? When this is correct, then this line would allocate 14 Bytes (13 Bytes for "Hello, world!" and one byte for 0xa - right?

Upvotes: 3

Views: 198

Answers (1)

Liam_LightChild
Liam_LightChild

Reputation: 81

Yes, in fact it does! It defines any amount of bytes, containing exactly what you give it.


There are three sections that are commonly used in assembly programs. .text, .data, and .bss. The .text section is for, well, code, and can be read or executed from, but not written. .data is for your initialized (like int a = 56 in C) variables. It is read and write, but no execute. .bss is for uninitialized (like int a in C) variables, and can be changed at runtime, and is zero initialized (instead of being initialized with a specific value). It has the same permissions as .data.

The .data section is fine for Hello World, but prefer to use .rodata (windows is .rdata, thanks comments), as it is read only.

Upvotes: 3

Related Questions