我想在运行时用 C 语言创建一个大约 1000 万行的数组,其精确大小只有在运行时才知道。这是它的第一个剪辑:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
printf("running\n");
long long size = atoi(argv[1]);
printf("%lld\n", size);
int myArray[size];
printf("allocated array\n");
for (long long i = 0; i< size; i++) {
myArray[i] = 1;
}
printf("Done");
}
我的问题是这个段错误。
>./a.out 100000000
running
100000000
Segmentation fault: 11
我想我必须做一个 malloc 才能让它工作,但我不太正确。
最佳答案
没有可移植的方法来检测自动分配的失败。在 Linux 上,您可以使用 ulimit -s
检查它并将其设置为无限制:ulimit -s unlimited
。
但即使这样也不能告诉您如此大的分配是否成功。更安全的方法是使用 malloc()
进行动态分配并检查分配是否成功:
int *myArray = malloc( size * sizeof *myarray);
if(!myarray) { /* allocation failed */}
关于C - 在运行时创建一个大小大于 10M 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23711763/