Hi I'm struggling to find out why my binary search implementation is seg faulting (I'm new to NASM assembly)
Sorry I know its not much of a MVP but I cant think of an appropriate way to make one in assembly.
%define n [ebp+8]
%define list [ebp+12]
%define low [ebp+16]
%define high [ebp+20] ; Parameters loading from the stack
binary_search:
push ebp
mov ebp, esp
mov ebx, n
mov edi, list
mov ecx, low
mov edx, high
cmp ecx, edx ; if (low > high)
jg .FIRST
mov eax, edx ; Next few lines for mid = low + (high - low)/2
sub eax, ecx
sar eax, 1 ; Will this give an appropriate index? (i.e is it floor division?)
add eax, ecx
lea esi, [edi+eax*4] ;Getting list[mid]
cmp ebx, [esi]; if (n == list[mid])
je .END
jl .SECOND
jg .THIRD
jmp .END
.FIRST:
mov eax, -1 ; return -1
jmp .END
.SECOND:
mov edx, eax ; return middle - 1
dec edx
jmp .CONTINUE
.THIRD:
mov ecx, eax ; low = mid - 1
dec ecx
jmp .CONTINUE
.CONTINUE:
push edx
push ecx
push edi
push esi
push ebx
call binary_search ; recursive call, causing the segfault.
pop ebx
pop esi
pop edi
pop ecx
pop edx
jmp .END
.END:
mov esp, ebp
pop ebp
ret
After commenting out different sections, I have determined that it is definitely something to do with my recursive call to binary_search that is causing the seg fault. (Found Inside .CONTINUE) What am I messing up insdie of the binary_search body that doesnt agree with multiple recursive calls?
The binary search algorithm:
binary_search(n, list, low, high)
if (low > high)
return -1
mid = low + (high - low) / 2
if (n == list[mid])
return middle;
if (n < list[mid])
high = mid - 1
else
low = mid + 1
return binary_search(n, list, low, high)
I know its a long shot, thanks :)
Edit: its 32-bit mode