I want to initialize an array in assembly with specific values. I tried doing it in a loop first but got junk in the arrays. I then tried doing it manually and got the same junk. I want the array to repeat 0 1 2 for an n amount of times. Here is some example code I tried.
This is my attempt at manully loading the array. The first value loads just fine. The second value however, loads in junk when I examine it in GDB.
sub esp, 260
mov [ebp - 12], dword -1
mov [ebp - 16], byte 0
mov [ebp - 17], byte 1
mov [ebp - 18], byte 2
mov [ebp - 19], byte 0
mov [ebp - 20], byte 1
mov [ebp - 21], byte 2
mov [ebp - 22], byte 0
mov [ebp - 23], byte 1
mov [ebp - 24], byte 2
mov [ebp - 25], byte 0
Here was my attempt at doing it automatically.
sub esp, 260
mov [ebp - 12], dword -1
again:
add [ebp - 12], dword 1
lea eax, [ebp - 16]
sub eax, [ebp - 12]
mov [eax], byte 0
add [ebp - 12], dword 1
lea eax, [ebp - 16]
sub eax, [ebp - 12]
mov [eax], byte 1
add [ebp - 12], dword 1
lea eax, [ebp - 16]
sub eax, [ebp - 12]
mov [eax], byte 2
cmp [ebp - 12], dword 255
jne again
jmp elsewhere
Using NASM, x86-32, Intel syntax.
EDIT: When I convert this code to store the array values as DWORDs instead of bytes both methods work. Why is that?
With NASM, you can easily initialise repeating data by using the times prefix. For instance, to repeat the sequence "0 1 2" n times as requested in your question, you can do something similar to the following:
section .data
my_array: times n db 0, 1, 2
Simply replace n by the constant value you want. More information about the times prefix can be found in the NASM Manual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With