C中的sizeof(数组):分段错误

齐天大*_*天大圣 3 c arrays

嗨,我从这段代码得到一个奇怪的分段错误:

int main(void){

  int array1[10000000];

  int n = sizeof(array1);

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我改变

int array1[10000000];
Run Code Online (Sandbox Code Playgroud)

int array1[1000000];  ( one less zero)
Run Code Online (Sandbox Code Playgroud)

该程序工作和打印4000000

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

这是因为C中的数组有最大大小吗?先感谢您

Spi*_*rix 16

int array1[10000000];
Run Code Online (Sandbox Code Playgroud)

对于你的堆栈太大而你溢出堆栈而

int array1[1000000];
Run Code Online (Sandbox Code Playgroud)

很大,但是当阵列适合它时,不会溢出堆栈.

请注意,堆栈的大小可能因系统而异,可以设置为特定大小.

解决方法:

  1. 制作阵列static.
  2. 使数组全局化.
  3. 使用mallocfrom 分配堆上的内存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!\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);
    
    Run Code Online (Sandbox Code Playgroud)