Question

Learning NASM Assembly for 32-bit Ubuntu.

Doing a function that simply prints the number you pushed into the stack before calling it:

SECTION .text
global main
main:
; -----------------------------------------------------------
; Main
; -----------------------------------------------------------
push    5
call    print_number

; -----------------------------------------------------------
; Exit
; -----------------------------------------------------------
mov EAX,1
int 0x80

; -----------------------------------------------------------
; Prints a number
; -----------------------------------------------------------
print_number:
push    EBP
mov     EBP,ESP

mov     EAX,4
mov     EBX,0
mov     ECX,[EBP + 8]
add     byte [ECX],'0'
mov     EDX,1
int     0x80

pop     EBP
ret

Keeps giving me a segmentation fault error.

Let's see... when I call the function, the stack should look like this:

  • 5
  • Return address

Then I push EBP:

  • 5
  • Return address
  • EBP

I want EBP to contain the address of the stack's base, so I do this:

mov EBP, ESP

So basically EBP is now an address to the stack's base. Since ECX needs to be the address of whatever I'm going to print, ECX should be EBP (the address of the stack's base) moved by 8 bytes so that it points to the 5 I want to print:

mov ECX,[EBP + 8]

And to print it I convert it to ASCII first:

add byte [ECX],'0'

I can't see the problem here. Why am I getting a segmentation fault?

Was it helpful?

Solution

mov ECX,[EPB+8] moves the value at location EPB+8 to ECX, which is not a valid address. It's just 5. You could just do:

mov   ECX,EPB
add   ECX,8
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top