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.
-
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 aint, 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();