繁体   English   中英

数组分段错误(核心转储)

[英]Segmentation fault (core dumped) with array

我的代码有问题。 我对该问题进行了一些研究,但我发现的解决方案似乎不能解决我的问题。 大多数解决方案都说这是由于数组没有索引。 这是我的代码。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int myrandom(int min, int max){
   return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}

int main() {
    clock_t begin = clock();
    int T1[1000000];
    int T2[1000000];
    int T3[1000000];
    
    for (int i = 0; i < 1000000; i++) {
        T1[i] = myrandom(-10, 10);
        T2[i] = myrandom(-10, 10);
        T3[i] = T1[i]*T2[i];//<-- Getting Segmentation fault (core dumped) here
    }
    
    
    
    
    clock_t end = clock();
    double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("Program terminé en %f Secondes\n", time_spent);
}

你溢出你的堆栈。

int T1[1000000];
int T2[1000000];
int T3[1000000];

每个语句在堆栈上分配1000000*sizeof(int)字节。 这会导致堆栈溢出和其他无关内存的损坏。

尝试使用动态分配:

int* T1=calloc(1000000,sizeof(int));
int* T2=calloc(1000000,sizeof(int));
int* T3=calloc(1000000,sizeof(int));

然后在使用后释放它。 (PS: calloc & Co. 出错时返回 NULL,所以检查错误)

free(T1);
free(T2);
free(T3);

正如@JCWasm 指出的那样,您正面临着一个 stackoverflow 问题。 默认情况下根本不允许您请求的静态内存(堆栈内存)量。 因此你的程序崩溃了。

供您参考:

  • gcc ,默认堆栈大小为 ~8MB参考
  • Windows (Visual Studio)上是 1MB 参考

现在,要解决您的问题,有两种可能的方法:

解决方案1:(更通用和推荐)

使用动态内存:

int* T1=malloc(1000000*sizeof(int));
int* T2=malloc(1000000*sizeof(int));
int* T3=malloc(1000000*sizeof(int));

解决方案2:(仅当由于某种原因无法使用动态内存时)

所有编译器都有一些增加堆栈大小的规定。 上面的链接演示相同。

  • 对于 gcc: > ulimit -s 32768 # sets the stack size to 32M bytes
  • 对于 Visual Studio:使用编译器标志/F设置堆栈大小,例如/F 32768

其他 2 个答案是正确的,提到您应该使用堆( malloc()calloc()free() )。 但是还有另一种解决方案,但这不是首选:使用static变量。 static变量存储在 .data 或 .bss 部分,因此它们不需要堆栈。 缺点是这个变量在运行过程中只存在一次,这使得static变量在使用多线程和其他场景时会出现问题。

尽可能选择堆,但有些独立环境可能没有堆。 但是,假设sizeof int == 2 ,您不太可能获得 2 MB 或更多 RAM,在这样的系统上,总 RAM 更有可能是 64 KiB 或类似的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM