段错误,大型阵列 [英] Segmentation Fault, large arrays

查看:136
本文介绍了段错误,大型阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#define N 1024
int main(){
  int i, j;
  int a[N][N];
  int b[N][N];
  for (i=0;i<N;i++){
    a[i][i]=i;
    b[i][i]=i;
  }
  for (i=0;i<N;i++)
    for(j=0;j<N;j++)
    {
         printf("%d", a[i][j]);
         printf("%d", b[i][j]);
    }
  return 0;
}

这计划是分段故障的原因,但如果我定义N作为1023,程序将正常工作。为什么会发生?

This program is a reason of segmentation fault, but if I define N as 1023, program will work correctly. Why it happens?

推荐答案

正在溢出堆栈。 2 * 1024 * 1024 * sizeof的(INT)是很多对于大多数系统。

You are overflowing the stack. 2 * 1024 * 1024 * sizeof(int) is a lot for most systems.

最简单的解决办法是使阵列静态

The simplest solution would be to make the arrays static.

static int a[N][N];
static int b[N][N];

其他方法:


  • 请全球阵列(这是本质上是相同以上)

  • 使用的malloc 在一个循环,当然记得免费

  • Make the arrays global (this is essentially the same as the above)
  • Use malloc in a loop and of course remember to free

int **a = malloc(N * sizeof *a);
for (i = 0; i < N; i++)
    a[i] = malloc(N * sizeof *a[i]);


这篇关于段错误,大型阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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