x86 Assembly/C: SIGABRT abortion when trying to create a dynamically allocated array

Viewed 91

I am writing an x86 Assembly function (Intel/AT&T syntax) that creates a dynamically allocated array and returns a poitner to it given two parameters:

  1. the number of integers into the array
  2. the default value in that array

Below is my C code (which calls the x86 Assembly function):

#include <stdio.h>
#include <stdlib.h>

int* allocateDynamicArray(int size, int value);

int main(void) {
    int* dynamicArray = allocateDynamicArray(3, 3);

    printf("%d", dynamicArray[0]);
    return EXIT_SUCCESS;
}

Below is my x86 Assembly code:

.extern malloc

.data
    numIntegers:
        .int 0

    defaultValue:
        .int 0

.text
# Defining a function addTwoMatrixCells
.global allocateDynamicArray
allocateDynamicArray:
    # Prologue
    push %ebp
    movl %esp, %ebp

    # Process in parameter 1: the number of integers stored in the array
    movl 8(%ebp), %ecx
    movl %ecx, numIntegers

    # Process in parameter 2: what to fill the array with
    movl 12(%ebp), %ecx
    movl %ecx, defaultValue

    # Allocate appropriate space for our dynamic array
    movl numIntegers, %edi
    imul $4, %edi
    push %edi
    call malloc
    pop %edi

    # EAX register now stores a pointer to our dynamically allocated array
    push %eax

    # The ECX register will store the index of the cell we are storing our number in
    movl $0, %ecx
    # The EDX register will store the default value
    movl defaultValue, %edx

    # Loop through each cell in the dynamically allocated array
    fillArray:
        # See if we have reached the last cell
        cmpl %ecx, numIntegers
        jl return

        # Move the default value into the cell's memory address
        push %ecx
        imul $4, %ecx
        addl %eax, %ecx
        movl %edx, (%ecx)
        pop %ecx

        # Shift to the next cell
        incl %ecx

        # Complete the loop
        jmp fillArray

    return:
        # We want to return a pointer to the dynamically allocated array
        pop %eax

        # Epilogue
        movl %ebp, %esp
        pop %ebp
        ret

    pop %eax

I am running my code on a 32-bit Linux machine. When I run my code, I get the following error:

CallAssemblyFromC.out: malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)

This seems strange, since I didn't have any memory allocation errors in my assembly program allocateDynamicArray.s and I believe I am resetting my stack pointers to the correct value as I pop the EDI register after calling malloc.

0 Answers
Related