iProgram
iProgram

Reputation: 6547

Why does this assembly code display a different number to what I specified?

I am learning how to use constants and have been able to load strings and integers into different registers. The only problem is, instead of 42 being displayed, 16777258 is being displayed instead. This is the same number all the time. If I change _number to a different value, I also get a different number displayed.

Why is this and what do I need to do?

This is my assembly code:

  .section  __TEXT,__text,regular,pure_instructions
  .globl  _main
_main:
  #Backup base and stack pointer
  pushq %rbp
  movq  %rsp, %rbp

  #Move arguments
  leaq  L_.str(%rip), %rdi
  movl  _number(%rip), %esi
  #Should calll printf("%d", 42)
  callq _printf

  #return 0
  xorl  %eax, %eax

  popq  %rbp
  retq
  .section  __TEXT,__cstring,cstring_literals
L_.str:
  .asciz  "%d"
  _number:
  .long 42

Upvotes: 0

Views: 43

Answers (1)

iProgram
iProgram

Reputation: 6547

What I had to do was move the below code

_number:
.long 42

from the .section __TEXT,__cstring,cstring_literals into .data. My code then looked like this:

  .section  __TEXT,__text,regular,pure_instructions
  .globl  _main
_main:
  #Backup base and stack pointer
  pushq %rbp
  movq  %rsp, %rbp

  #Move arguments
  leaq  L_.str(%rip), %rdi
  movl  _number(%rip), %esi
  #Should calll printf("%d", 42)
  callq _printf

  #return 0
  xorl  %eax, %eax

  popq  %rbp
  retq

  .data
  _number:
  .long 42

  .section  __TEXT,__cstring,cstring_literals
L_.str:
  .asciz  "%d"

Upvotes: 1

Related Questions