I am trying to dynamically allocate memory to a 2-D array through creating a pointer to a pointer. In other words, I am trying to emulate the following C code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 3, i, j, count;
int **arr = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
}
I was breaking down this problem into two problems:
- Allocating memory for the entire matrix:
int **arr = (int **)malloc(r * sizeof(int *));
- Allocating memory for each row in the matrix:
for (i=0; i<r; i++) arr[i] = (int *)malloc(c * sizeof(int));
I think I can finish the first part, because I can dynamically allocate a section of memory through calling the C malloc
function in my Assembly code (for example, 12 bytes here, since in the C example I am using, the matrix has 3 rows and an integer pointer (int*
) has 4 bytes of space):
movl $12, %edi
extern malloc
call malloc
however at the second part, how would I go about allocating memoery at each row? The code above is going to return a pointer to the matrix in the EAX register, so I was thinking about:
movl ($eax), %eax
Which would return the memory address of the first row. How do I then allocate space at that specific memory address? From my basic knowledge of Assembly so far, malloc
can only allocate memory and then return a pointer to a memory address, but I'm not sure how to use that command to allocate memory at a pointer to a specific memory address.