Home > Enterprise >  How to pass array from assembly to a C function
How to pass array from assembly to a C function

Time:09-22

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;
}

CodePudding user response:

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

  • Related