Reputation: 11
I'm trying to write a linear search subroutine in x64 assembly that return the index of the target It takes four parameter. This function will scan through an array iteratively until it finds the target element or reaches the end of the array. The function takes in three parameters. The first parameter is a pointer to an int array. The second parameter is an integer representing the size of the array. The third parameter is an integer representing the target element to find in the array. The return type of this fuction is int, and will be the index into the array that the target was found, or -1 if it wasn’t
I wrote a psudeocode for this
int linearSearch(int * arr, int size, int target){
int a;
int index = -1;
for(int i = 0; i < size; i++){
if(arr[i] == target){
index = i;
break;
}
}
return index;
}
And here is my code for that
global linearSearch
linearSearch:
;the prologue
xor rax, rax ;zero out the return address
xor r10, r10 ;zero out the counter
linearSearchIterative:
;function body
mov rax, -1 ;int index = -1 if not found
cmp r10, rsi ;compare counter i with the size
je done ;done with the program
cmp rdx, [rdi+4*r10] ;compare target with arr[i]
je linearSearchAlter ;jump to the index fixing part if arr[i] == target
inc r10 ;i++
jmp linearSearchIterative ;go back to the start of the loop
linearSearchAlter:
;This part change the return index to where the target is
mov rax, r10 ;index = i
jmp done ;end the loop
done:
ret
However, the subroutine is only returning -1, which is not expected. I'm using a testing cpp file to test my code which should give the folliowing expected result
#include <iostream>
#include <cstring>
using namespace std;
extern "C" int linearSearch(int * arr, int size, int target);
int main(){
int size;
// prompt for array size
cout << "Enter the array size: ";
cin >> size;
int * arr = new int[size];
// read in array values
for(int i = 0; i < size; i++) {
cout << "Enter value " << i << ": ";
cin >> arr[i];
}
int target;
// prompt for target
cout << "Enter target to search for: ";
cin >> target;
int ind = linearSearch(arr, size, target);
cout << ind << endl;
if (ind > -1)
cout << "\nFound " << target << " at index " << ind << endl;
else
cout << "\nDid not find " << target << endl;
return 0;
}
The expected result should be (I add a print statement to check the value of the index)
Enter the array size: 5
Enter value 0: -7
Enter value 1: 2
Enter value 2: -39
Enter value 3: 12
Enter value 4: 8
Enter target to search for: 2
1
Found 2 at index 1
Instead, my result is (I add a print statement to check the value of the index)
Enter the array size: 5
Enter value 0: -7
Enter value 1: 2
Enter value 2: -39
Enter value 3: 12
Enter value 4: 8
Enter target to search for: 2
-1
Did not find 2
So it seems that the subroutine always return -1 instead of the index of the target. Where should the problem be? Thanks
Upvotes: 0
Views: 290