无法分配内存 [英] Could not allocate memory

查看:270
本文介绍了无法分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C code,我分配的二维数组的内存双E [2000] [2000]; 但是当我运行它得到一个运行时错误分割故障(核心转储),当我减少数组大小某处大约900那么code运行正常。

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 I reduce the array size to somewhere around 900 then the code runs fine.

为什么它显示运行时错误,因为双重利用64位的内存(IEEE标准),因此code大约需要32MB这是没有太大相比RAM size.And如果不是在C支持的话应该怎么我继续,如果我有存储数据的我的最大数量为400万每个是浮点数。

Why it is showing runtime error since double take 64 bits memory (IEEE standard) so the code should take approximately 32MB which is not much compared to the ram size.And if it is not supported in C then how should I proceed if my maximum number of data that I have to store is 4000000 each are floating point numbers.

推荐答案

您声明E上一个局部变量?如果是这样,你用完堆栈内存。

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
}

使用动态分配的:

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。如果你想保持你的数据在连续的方式,有一个从的木村拓哉Ooura的FFT包

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);
}

在你刚刚叫

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

free_2d(E);

这篇关于无法分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆