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

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

问题描述

#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.

最简单的解决方案是将数组设为static.

The simplest solution would be to make the arrays static.

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

其他方法:

  • 使数组全局化(这与上面的基本相同)
  • 在循环中使用malloc,当然记得free

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

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

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