Allocating and initializing a 2D array dynamically using a double pointer

84 Views Asked by At

I'm trying to create a 2D array (5 rows and 2 cols) dynamically. At the time of allocating the memory there's no sort of problem. However, while assigning actual values to the array I got a Segmentation Fault error. While debugging I got to realize that the error pops up when i in the for loop has value 4

How can it be possible to get a segmentation fault error even after allocating with no problem the memory that will be used by the array?

 #include <stdio.h>
 #include <stdlib.h>
 
 int main(int argc, char *argv[]){
     int **ptr = (int **)malloc(sizeof(int)*5);
     for(int i = 0; i<5; i++){
         ptr[i] = (int *)malloc(sizeof(int)*2);
     }
     
     for(int i = 0; i<5; i++){
         for(int j = 0; j<2; j++){
             ptr[i][j] = i;
         }
     }
     return 0;
 } 
2

There are 2 best solutions below

2
chux - Reinstate Monica On BEST ANSWER

How can it be possible to get a segmentation fault error even after allocating with no problem the memory that will be used by the array?

Code did not allocate correctly. sizeof(int)*5 is the wrong size in OP's code.

  • Avoid allocation errors. Size to the referenced object, not the type. It is easier to code right the first time, review and maintain. In OP's case sizeof ptr[0] is the correct size, the size of a pointer. sizeof(int) is incorrect as it is the size of a int, yet the size of a pointer is needed here.

  • Casting not needed.

  • Better code checks for allocation failures.

    // int **ptr = (int **)malloc(sizeof(int)*5);
    int **ptr = malloc(sizeof ptr[0] * 5);
    if (ptr == NULL) Handle_OutOfMemory();
2
gulpr On

Allocating and initializing a 2D array

An array of pointers is not a 2D array.

To allocate 2D array I would use pointer to array:

void initArray(size_t rows, size_t cols, int (*array)[cols])
{
    if(array && rows && cols)
        for(size_t row = 0; row < rows; row++)
            for(size_t col = 0; col < cols; col++)
                array[row][col] = rand() % 100;
}

void printArray(size_t rows, size_t cols, int (*array)[cols])
{
    if(array && rows && cols)
        for(size_t row = 0; row < rows; row++)
        {
            for(size_t col = 0; col < cols; col++)
                printf("%03d ", array[row][col]);
            printf("\n");
        }
}

int main(void)
{
    int (*ptr)[COLS] = malloc(ROWS * sizeof(*ptr));
    if(ptr)
    {
        printf("Allocation OK\n");
        srand(time(NULL));
        initArray(ROWS, COLS, ptr);
        printArray(ROWS, COLS, ptr);
    }
    else
        printf("Allocation FAILED\n");

    free(ptr);
}