Segmentation fault (core dumped) (C, and C++ programming)
Segmentation fault (core dumped) (C, and C++ programming)
This is popular error in programming with arrays. It comes due to overshooting the memory limit by declaring the array in static memory allocation. You can solve this by using the dynamic memory allocation of the arrays. All you have to do is declare your array as follow:
For (C programming)
For one dimensional array:
int *a;
a = (int *)malloc((array_size)*sizeof(int));
double *b;
b = (double*)malloc(array_size)*sizeof(double));
Then after the use of arrays free the memory by the following;
free(a);
free(b) ;
For two dimensional array:
For an array like a[ row_numbers ][ column_numbers ]
int** a = malloc((row_nimbers) * sizeof(int*));
for (i=0;i<row_nimbers,i++) {
a[ i ] = malloc((column_nimbers)* sizeof(int));
}
Then after the use of arrays free the memory by the following;
for(i = 0; i <row_nimbers; i++) {
free(a[ i ]);
}
For (C++ programming)
int* x = new int[ N ];
Then after the use of arrays free the memory by the following;
delete []x;
For two dimensional array of type y[ N ][ M ]
int** y = new int*[ M ];
for(int i = 0; i < M; ++i)
y[ i ] = new int[ N ];
and at the end don't forget to write at the end
for (int i = 0; i < M ; ++i){
delete [ ] y[ i ];
}
Comments
Post a Comment