arrayscpointerssegmentation-faultdouble-pointer

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


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;
 } 

Solution

  • 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.

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