【问题标题】:How to allocate more memory to C code如何为 C 代码分配更多内存
【发布时间】:2017-03-22 09:22:36
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    long int length = atol(*++argv);

    long int a[length];

    // write and read it, so it doesn't get optimized out:
    for (int i = 0; i < length; ++i)
        a[i] = i;    
    for (int i = 0; i < length; ++i)
        if (a[i] != i)
            return 1;
}

上面的程序在大多数情况下都会运行,但是当我尝试使用大量数字(例如 1967791)初始化数组 a 时,我遇到了分段错误。有没有办法可以为程序分配更多内存,这样就不会发生这种情况?

我正在使用 Linux 的虚拟机上运行此程序。

【问题讨论】:

  • 使用malloc 而不是将数组放入堆栈。您通常可以从malloc 中获得比从堆栈中获得的更多内存。
  • 对我来说argv[1]*++argv 更容易阅读。也可能不希望更改 argv

标签: c arrays memory segmentation-fault


【解决方案1】:

你需要在堆上分配内存,而不是在栈上:

  long int *a = malloc(array_length * sizeof *a);

不要忘记在不再需要它时free()它。

【讨论】:

  • 在C语言中,不要强制转换malloc的返回值,这样可以隐藏bug。
猜你喜欢
  • 2013-09-30
  • 1970-01-01
  • 2010-09-19
  • 2011-01-05
  • 2017-11-15
  • 2018-10-06
  • 2010-10-24
  • 2012-09-24
  • 2020-12-30
相关资源
最近更新 更多