Could not allocate memory

前端 未结 3 1520
-上瘾入骨i
-上瘾入骨i 2021-01-22 17:15

In my C code I am allocating memory for 2d array double E[2000][2000]; but when I run it gets a runtime error Segmentation fault(core dumped) and when

3条回答
  •  盖世英雄少女心
    2021-01-22 18:19

    Are you declaring E as a local variable ? If so, you're running out of stack memory.

    void func()
    {
        double E[2000][2000]; /// definitely an overflow
    }
    

    Use dynamic allocation:

    double* E = malloc(2000 * 2000 * sizeof(double));
    /// don't forget to "free(E);"  later
    

    Or if you need the 2D array, use a zig-zag:

    double** E = malloc(2000 * sizeof(double*));
    
    /* check that the memory is allocated */
    if(!E)
    {
        /* do something like exit(some_error_code);  to terminate your program*/
    }
    
    for(i = 0 ; i < 2000 ; i)
    {
          E[i] = malloc(2000 * sizeof(double));
    
         /* check that the memory for this row is allocated */
         if(!E[i])
         {
            /* do something like exit(some_error_code);  to terminate your program*/
         }
    }
    

    Then the deallocation is a little more complicated:

    for(i = 0 ; i < 2000 ; i)
    {
          free(E[i]);
    }
    
    free(E);
    

    P.S. If you want to keep all of you data in a continuous way, there's a trick (code from Takuya Ooura's FFT Package)

    double **alloc_2d(int n1, int n2)
    {
        double **ii, *i;
        int j;
    
        /* pointers to rows */
        ii = (double **) malloc(sizeof(double *) * n1);
    
        /* some error checking */
        alloc_error_check(ii);
    
        /* one big memory block */
        i = (double *) malloc(sizeof(double) * n1 * n2);
    
        /* some error checking */
        alloc_error_check(i);
    
        ii[0] = i;
        for (j = 1; j < n1; j++) {
            ii[j] = ii[j - 1] + n2;
        }
        return ii;
    }
    
    void free_2d(double **ii)
    {
        free(ii[0]);
        free(ii);
    }
    

    The you just call

    double** E = alloc2d(2000, 2000);
    

    and

    free_2d(E);
    

提交回复
热议问题