How to allocate memory for a large two-dimensional array in C?

Question:

I am working with a large 2 dimensional array.

In the case when it is 30 x 200, everything counts. With large volumes, the program crashes … I was advised to use memset (), but something does not help much … Maybe you have any 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;
}

Answer:

In general, the code is correct, but you need to add a check when allocating memory: this is necessary because memory may simply not be enough, in which case the program will crash, because writing to non-existent memory will occur. That is, whenever malloc is called, you need to 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 remember to free the memory allocated by malloc inside the loop, otherwise there will be leaks.

Scroll to Top