Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

  • 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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading