How to allocate memory for a large two-dimensional array in C?
I'm working with a large two-dimensional array.
In the case where it is 30 x 200 in size, everything counts. At large volumes, the program crashes... I was advised to use memset(), but something doesn't really help... Maybe you have some ideas?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
double **B;
int main (int argc, char *argv[])
{
int N, n_A;
N = 32;
n_A = 350; /* если сделать n_A = 200, то все работает */
B = (double **)malloc(N * sizeof(double *));
for(i = 0; i < N; i++)
{
B[i] = (double *)malloc(n_A * sizeof(double));
memset(B[i], 0, n_A * sizeof(double));
}
free(B);
return 0;
}
3 answers
In general, the code is correct, but you need to add a check when allocating memory: this is necessary, because the memory may simply not be enough, and in this case the program will crash, because it will write to non-existent memory. That is, whenever a call to malloc occurs, you must check that the return value is not NULL.
B = (double **)malloc(N * sizeof(double *));
/* Проверить, что память выделена */
if (B != NULL)
{
for(i = 0; i < N; i++)
{
B[i] = (double *)malloc(n_A * sizeof(double));
/* Проверить, что память выделена */
if (B[i] != NULL)
{
memset(B[i], 0, n_A * sizeof(double));
free(B[i]);
}
}
free(B);
}
In addition, you must not forget to release the memory allocated by malloc inside the loop, otherwise there will be leaks.
All this can be done in one line
double * B;
B = (double *) calloc (N * n_A, sizeof(double));
free (B);
Instead of calling a bunch of functions, you call one that immediately allocates memory for the entire data array and resets it.
The data is accessed using the formula
double a;
a = *(B + i * n_A + j);
Where i is the row number, j is the column number
For large volumes, the program crashes...
The local buffer (more precisely, the size of the stack frame) should not be larger than one page. Otherwise, there will be a call outside the watch page of the stack, it will not be expanded, and an exception will occur.