嗨,我从这段代码中得到了一个奇怪的分段错误:
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 中数组有最大大小吗?先感谢您
int array1[10000000];
对于你的堆栈来说太大并且你溢出了你的堆栈,而
int array1[1000000];
很大,但不会溢出堆栈,因为数组适合其中。
请注意,堆栈的大小可能因不同系统而异,并且可以设置为特定大小。
解决方法:
- 制作数组
static
.
- 使数组全局化。
-
使用在堆上分配内存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!\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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)