Skip to content

Instantly share code, notes, and snippets.

@seisvelas
Created December 3, 2020 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seisvelas/b838dba2ea283bbe7e729d1a17e7980e to your computer and use it in GitHub Desktop.
Save seisvelas/b838dba2ea283bbe7e729d1a17e7980e to your computer and use it in GitHub Desktop.
assembly toy problem
global main
extern printf
SECTION .text
small_enough:
mov rax, 1
add rsi, 1
;rdi array, rsi array length, rdx limit
loop:
;compare current element of array to limit
mov r8, [rdi]
;move rdi to point to next element
add rdi, 8
;r8 is current element
cmp r8, rdx
jg fail
;check loop condition
sub rsi, 1
cmp rsi, 1
jne loop
;unless you jump to fail, we should skip it
jmp return
fail:
mov rax, 0
return:
ret
main:
mov rdi, array
mov rsi, 2
mov rdx, 200
call small_enough
push rax
mov rdi, format
mov rsi, [rsp]
xor rax, rax
call printf
pop rax
ret
format: db "%d", 10, 0
array: dq 66, 101
@seisvelas
Copy link
Author

This works on my machine (prints "1") but on CodeWars, I fail the test. No idea why. Here is the problem on CodeWars: https://www.codewars.com/kata/57cc981a58da9e302a000214/train/nasm

@seisvelas
Copy link
Author

One possibility is that in my local code I recreate the test data using the data section. But in the test, it's an array literal which would be on the stack. Maybe those work differently. Also they define the type as int. My local numbers are 64 bit, but I don't know if that's true of C ints. In fact, I believe this is the problem.

Based on this StackOverflow discussion: https://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes

The size of a C int is almost certainly not 8 bytes on CodeWars. So it'll be 2 or (more likely) 8 bytes. But changing the iteration amount won't be enough, I'll also have to use 4 byte registers to store these 4 byte numbers in, which explains what some other people on CodeWars were doing. Interesting!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment