的sizeof(数组)在C:分段故障 [英] sizeof(array) in C: segmentation fault

查看:103
本文介绍了的sizeof(数组)在C:分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我从中得到code一个奇怪的分段错误:

  INT主要(无效){  INT数组1 [千万]  INT N = sizeof的(数组1);  的printf(%d个\\ N,N);    返回0;
}

但是,如果我更改

  INT数组1 [千万]

  INT数组1 [百万] (少了一个零)

该项目工程,并打印400万

我运行它在Fedora 21(64位)

这是因为在C数组的最大尺寸?谢谢你在前进


解决方案

  INT数组1 [千万]

是你的栈太大,你溢出你的筹码,而

  INT数组1 [百万]

是大的,但如在数组中它适合不溢出的堆

请注意,该堆栈的大小可以在不同的系统而改变,并且可以设置为特定尺寸。

方法来解决它:


  1. 请在阵列静态

  2. 请在阵列全球性的。

  3. 分配使用的malloc 文件stdlib.h 的堆内存:

     为int *数组1;
    数组1 =的malloc(10000000 *的sizeof(INT));如果(数组1 == NULL)/ *如果`malloc`无法分配内存* /
    {
        的fputs(哎呀呀`malloc`分配内存失败!,标准错误);
        出口(-1); / *用`-1`返回值退出程序;需要`stdlib.h` * /
    }/ *使用数组,并使用后,释放它使用* /免费(数组1);


Hi i get a weird segmentation fault from this code:

int main(void){

  int array1[10000000];

  int n = sizeof(array1);

  printf("%d \n", n );

    return 0;
}

However if i change

int array1[10000000];

to

int array1[1000000];  ( one less zero)

The program works and prints 4000000

I'm running it on Fedora 21(64bits)

Is this because there is a maximum size for array in C? Thank you in advance

解决方案

int array1[10000000];

is too large for your stack and you overflow your stack whereas

int array1[1000000];

is large, but does not overflow your stack as the array fits in it.

Note that the size of the stack can vary on different systems and can be set to a particular size.

Methods to solve it:

  1. Make the array static.
  2. Make the array global.
  3. Allocate memory on the heap using malloc from stdlib.h:

    int *array1;
    array1 = malloc(10000000 * sizeof(int));
    
    if(array1 == NULL) /* If `malloc` failed to allocate memory */
    {
        fputs("Oops! `malloc` failed to allocate memory!", stderr);
        exit(-1); /* Exit the program with a return value of `-1` ; Requires `stdlib.h` */
    }
    
    /* Use the array and after use, free it using */
    
    free(array1);
    

这篇关于的sizeof(数组)在C:分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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