I'm having some trouble understanding the functionality of malloc
and perhaps that's why I'm seeing this issue, but hopefully someone here can help me understand.
I am allocating a 2D array using the following function:
int16_t** create_2d_array(uint8_t num_rows, uint16_t num_cols){
uint8_t i = 0;
int16_t **arr = (int16_t **)malloc(num_rows * sizeof(int16_t *));
for(i=0; i<num_rows; i++) {
arr[i] = (int16_t *)malloc(num_cols * sizeof(int16_t));
}
return arr;
}
I am calling this function like so:
twoD = create_2d_array(4, 512);
If I stop my code at the beginning of the for loop and check the contents of arr
using my GDB terminal, then I get the following:
gdb $ p/x arr[0]
$96 = 0x2001fa00
gdb $ p/x arr[1]
$97 = 0x0
gdb $ p/x arr[2]
$98 = 0x0
gdb $ p/x arr[3]
$99 = 0x0
This implies, at least to me, that arr[0]
was allocated properly, but not the other elements of arr
.
Isn't malloc
supposed to determine if the size requested can be allocated and if not, then it should return a NULL
pointer? At least that's my understanding of malloc
. Is there something I'm doing wrong?
As a test, I executed the following line:
twoD_temp = create_2d_array(2, 4);
Again I stop the execution at the beginning of the for loop and print the contents of arr
.
gdb $ p/x arr[0]
$121 = 0x2001fa00
gdb $ p/x arr[1]
$122 = 0x2001fa10
This is what I would expect. First index is a valid pointer, and the second index is also a valid pointer since I created an array of pointers.
After the for loop executes I print the same contents:
gdb $ p/x arr[0]
$125 = 0x2001fa00
gdb $ p/x arr[1]
$126 = 0x2001fa10
This is still the same which is what I would expect. The only difference now is that there is memory allocated for the columns.