Trying to understand x86 GAS assembly, why doesn't this work?

Viewed 45

For information, the assembly (.s) code wont work without the C (.c) code. The C code makes a call to asm_function() which in the assembly code is FUNC(asm_function). I know C code well enough, but i am the greenest of green in assembly. My question is, why do i get segmentation fault, instead of asm_function() returning a value.

Here is the C code:

extern int asm_function();

int *create_array(int size){
    int *array = malloc(sizeof(array));
    int i = 1;
    for(int i = 1; i < size; i++){
        array[i] = i;
    }
    return array;
}

int main(int argc, char **argv) {
    
    int index = 5;
    int size = 10;
    int *data = create_array(size);
    int value = asm_function(index, size, data);
    printf("Value %d\n", value); 
}

Here is the assembly code:

FUNC(asm_function):
    pushl %ebp
    movl %esp, %ebp

    pushl %ebx
    pushl %esi
    pushl %edi

    movl 8(%ebp), %ecx # data
    movl 12(%ebp), %edi # size
    movl 16(%ebp), %eax # index

    movl (%ecx, %edi, 4), %edx # data (index)
    
    movl $1, %esi # i = 1

    jmp loops

    loops:
        cmpl 12(%ebp), %esi # if (i = size)
        jge exit # jump if (i >= size)

        movl %esi, %eax # array[i] = i
        incl %esi # i++

        jmp loops

    exit:
        popl %edi
        popl %esi
        popl %ebx
        popl %ebp
        ret
0 Answers
Related