C语言中的sizeof(array):分段错误

3

嗨,我从这段代码中得到了一个奇怪的分割故障:

int main(void){

  int array1[10000000];

  int n = sizeof(array1);

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

    return 0;
}

然而,如果我更改了

int array1[10000000];

to

int array1[1000000];  ( one less zero)

这个程序运行正常并且输出了4000000。

我在Fedora 21(64位)上运行它。

这是因为在C语言中数组有一个最大的大小限制吗?谢谢。


2
栈通常只有几兆字节的大小,你无法将一个38MB的数组放在上面。 - dtech
2个回答

16
int array1[10000000];

当栈空间不足以存储数据时,数据的大小超过了栈的容量,导致发生栈溢出错误

int array1[1000000];

数组很大,但不会溢出堆栈,因为它适合堆栈。

请注意,堆栈的大小可能因不同系统而异,并且可以设置为特定大小。

解决方法:

  1. 将数组声明为static
  2. 将数组声明为全局变量。
  3. 使用stdlib.h中的malloc在堆上分配内存:
int *array1;
array1 = malloc(10000000 * sizeof(int));

if(array1 == NULL) /* If `malloc` failed to allocate memory */
{
    fputs("Oops! `malloc` failed to allocate memory!\n", 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);

好的,谢谢。但是我能声明一个大小为10000000的数组吗? - 齐天大圣
@Jackddddd,已更新答案。 - Spikatrix
如答案所示,在函数之间写上“static”(这样只能在此文件中看到)“array1 [10000000];”。 - user3629249

2

另一种解决方法是使用setrlimit增加栈大小。标准大小在我的Linux上至少为8 MB。

#include <stdio.h>
#include <errno.h>
#include <sys/resource.h>

static int setstacksize(rlim_t stacksize)
{
    struct rlimit rl;
    int res;

    if ((res = getrlimit(RLIMIT_STACK, &rl)) != 0) {
        fprintf(stderr, "getrlimit result = %d, errno = %d\n", res, errno);
        return res;
    }
    if (rl.rlim_cur >= stacksize) return res;
    rl.rlim_cur = stacksize;
    if ((res = setrlimit(RLIMIT_STACK, &rl)) != 0) {
        fprintf(stderr, "setrlimit result = %d, errno = %d\n", res, errno);
    }
    return res;
}

static int func(void){

    int array1[10000000];
    int n = sizeof array1;

    printf("%d\n", n);
    return 0;
}

int main(void){
    setstacksize(48 * 1024 * 1024);
    func();
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接