Pregunta

I've come across some nasm assembly examples. This is a classic Hello World program:

; ----------------------------------------------------------------------------
; helloworld.asm
;
; This is a Win32 console program that writes "Hello, World" on one line and
; then exits.  It needs to be linked with a C library.
; ----------------------------------------------------------------------------

        global  _main
        extern  _printf

        section .text
_main:
        push    message
        call    _printf
        add     esp, 4
        ret
message:
        db      'Hello, World', 10, 0

One thing I do not understand is why is only four added to esp after printf is executed? It's supposed to flush out the message var from the stack if I understand right. The whole db variable is pushed onto stack, and obviously it takes more than 4 bytes. (I've referred to the accepted answer to this question: what is the syntax to define a string constant in assembly?)

I'm sure this is an extremely stupid question for an experienced assembly programmer.

¿Fue útil?

Solución

message is the address of that text, not the text itself. When you execute push message, it decrements the stack pointer by four and puts that address at that location.

Then following the call, it cleans up by simply adding four back to the stack pointer, effectively removing message from the stack.

In any case, like hordes of C programmers seem to miss, there's no real point using printf if you're outputting a fixed string followed by a newline, the puts function is a better choice:

; ----------------------------------------------------------------------------
; helloworld.asm
;
; This is a Win32 console program that writes "Hello, World" on one line and
; then exits.  It needs to be linked with a C library.
; ----------------------------------------------------------------------------

        global  _main
        extern  _puts

        section .text
_main:
        push    message
        call    _puts
        add     esp, 4
        ret
message:
        db      'Hello, World', 0

Otros consejos

It's only the address of the message label that is pushed to the stack, not a copy of what it is pointing to.

The label message only specifies an address in the program, not the data that is defined after it. The label doesn't contain any information about the data that follows (e.g. the type or length), it's only a reference to memory location.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top