0

I am new to assmbly, and I have some problem. I compiled the following code with GCC:

.intel_syntax noprefix

.section .data
number:
    .int 65

message:
    .ascii "The number is %d %d.\n\0"

.section .text
    .globl  _main

_main:
    push ebp

    lea eax, [message]
    mov ebx, number
    mov [esp + 8], ebx
    add ebx, 1
    mov [esp + 4], ebx
    mov [esp], eax

    call _printf

    pop ebp
    xor eax, eax
    ret

It can display the message The number is 66 65. on the console, but the vscode show some errors without more information.

vscode output

I tried to remove the line mov [esp + 4], ebx, and the error that vscode showed fixed.

.intel_syntax noprefix

.section .data
number:
    .int 65

message:
    .ascii "The number is %d %d.\n\0"

.section .text
    .globl  _main

_main:
    push ebp

    lea eax, [message]
    mov ebx, number
    mov [esp + 8], ebx
    add ebx, 1
    mov [esp], eax

    call _printf

    pop ebp
    xor eax, eax
    ret

vscode output after fixing

Can anyone help me to solve the problem and explan it? Thank you!

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
5y9uodh8
  • 3
  • 5
  • The red vscode symbol indicates a nonzero exit code from the program. Blue indicates an exit code of 0. It's not clear to me why your code exits 0 in one case but not the other. The return value of _main (which is also used as the exit code by gcc) is in eax, which is cleared in both cases. See https://stackoverflow.com/a/51353096/2708313 – rpatel3001 Apr 16 '23 at 08:37
  • 2
    Your function overwrites its return address and then tries to `ret`, so it'll crash. Look at where `ESP` is pointing when `mov [esp+4], ebx` runs, because you're using `mov` instead of `push` and didn't reserve any stack space first. – Peter Cordes Apr 16 '23 at 09:31

1 Answers1

0

Thanks for Mr./Ms. Peter's answer (and also thanks for Mr./Ms. rpatel3001's answer), I solve this problem by reserving the stack space.

Here is the code after modified:

.intel_syntax noprefix

.section .data
number:
    .int 65

message:
    .ascii "The number is %d %d.\n\0"

.section .text
    .globl  _main

_main:
    push ebp
    sub esp, 8 # <-----

    lea eax, [message]
    mov ebx, number
    mov [esp + 8], ebx
    add ebx, 1
    mov [esp + 4], ebx
    mov [esp], eax

    call _printf

    add esp, 8 # <-----

    pop ebp
    xor eax, eax
    ret

5y9uodh8
  • 3
  • 5