I wrote a simple program that takes an array length, populate the array by storing it at using esp decrement (so on the stack) then it print the array. My code is the following:
.686
.xmm
.model flat, C
OPTION CaseMap:None
include ../masm32/libs/windows.inc
include ../masm32/libs/kernel32.inc
include ../masm32/libs/user32.inc
include ../masm32/libs/msvcrt.inc
include ../masm32/libs/masm32.inc
EXTERN printf:PROC
EXTERN scanf:PROC
.data
str_insert_array_length db "Insert Array Length: ",0
str_insert_value db 10,"Insert Value: ",0
str_input_format db "%d",0
str_format_print db "%d",10,0
input_length DWORD 0
input_value DWORD 0
.code
main PROC
push ebp
mov ebp,esp
push offset str_insert_array_length
call printf
add esp,4
push offset input_length
push offset str_input_format
call scanf
add esp,8
mov edi,[input_length]
array_input:
push offset str_insert_value
call printf
add esp,4
push offset input_value
push offset str_input_format
call scanf
add esp,8
mov eax, [input_value]
push eax
dec edi
jnz array_input
mov edi,[input_length]
sub esp,4
print_array:
mov edx,[esp+4*edi]
push edx
push offset str_format_print
call printf
add esp,8
dec edi
jnz print_array
add esp,4
pop ebp
invoke ExitProcess,0
main ENDP
end
As you can see before the "print_array" part I need to sub esp by 4 because otherwise I get the current return address printed as the first element of the array (because it will be "esp+20" and the array starts at "esp+16") instead of the last element printed. After the part I add 4 to esp to get it to the right position again. Is that the correct way to print the array or there is another method instead of sub/add esp by 4 before/after the code part?
Also if I want to save the array on the Heap, how can I do it? I know I need to declare a variable, but this variable should have dynamic length because the length of the array is dynamic so I don't know how to get this :/