2

I wanna pass an array defined in assembly code to a C function, but i'm getting a segment violation error when i try to access that array in my C code. Here is the assembly code (i'm using nasm):

%include "io.inc"
extern minimo ;My C function
extern printf

section .data
   array db 1, 2, 3, 4, 5 ;My array
   alen db 5               ;My array length
   fmt db "%d", 10, 0      ;Format for the printf function

section .text
global CMAIN
CMAIN:
   xor eax, eax

   mov ebx, [alen]
   mov ecx, [array]
   
   push ebx
   push ecx
   call minimo
   add esp, 8

   push eax
   push fmt
   call printf
   add esp, 8
   
   mov eax, 1
   mov ebx, 0
   int 80h

And here is my C code:

int minimo(int *array, int size){
   int ret = array[0];
   for (int i = 1; i < size; i++){
      if(array[i] < ret){
         ret = array[i];
      }
   }
   return ret;
}
4
  • 1
    mov ecx, [array] moves the first 4 bytes of array into ECX. If you want to put the address in ECX it would be mov ecx, array. You are also moving the 4 bytes starting from alen into EBX. If you mean to to do that make alen a dd and not a db Commented Sep 21, 2022 at 16:36
  • Is this on Windows or Linux? Commented Sep 21, 2022 at 16:38
  • 3
    Another weird thing is you made array an array of bytes (using db) but your function takes an array of ints. If you want an array of ints you will have to change array to be dd instead of db. Commented Sep 21, 2022 at 16:43
  • @MichaelPetch you are right, "mov ecx, array" solved my issue, like PIRIQITI pointed out as well. And yes, i changed it to dd instead of db as you suggested because i was not getting correct output (it was throwing weird numbers) but with this correction now i see the numbers i placed in the output. Thanks Commented Sep 21, 2022 at 19:41

1 Answer 1

2

mov ecx, [array] moves the value sitting on the location "array" points to, so you need to move an address mov ecx, array will do

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.