C中的sizeof(数组):分段错误
嗨,我从这个代码中得到一个奇怪的分段错误:C中的sizeof(数组):分段错误,c,arrays,C,Arrays,嗨,我从这个代码中得到一个奇怪的分段错误: int main(void){ int array1[10000000]; int n = sizeof(array1); printf("%d \n", n ); return 0; } 但是如果我改变 int array1[10000000]; 到 该程序可运行并打印400万份 我在Fedora 21(64位)上运行它 这是因为C中的数组有一个最大大小吗?先谢谢你 int array1[10000000]; 对于堆
int main(void){
int array1[10000000];
int n = sizeof(array1);
printf("%d \n", n );
return 0;
}
但是如果我改变
int array1[10000000];
到
该程序可运行并打印400万份
我在Fedora 21(64位)上运行它
这是因为C中的数组有一个最大大小吗?先谢谢你
int array1[10000000];
对于堆栈来说太大,并且堆栈溢出
int array1[1000000];
是大的,但不会溢出堆栈,因为数组适合它
请注意,堆栈的大小在不同的系统上可能有所不同,并且可以设置为特定的大小
解决方法:
为静态
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);
解决此问题的另一种方法是使用
setrlimit
增加堆栈大小。标准大小是8MB,至少在我的Linux上是这样
#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;
}
#包括
#包括
#包括
静态整数设置堆栈大小(rlim\U t堆栈大小)
{
结构rlimit-rl;
国际关系;
如果((res=getrlimit(RLIMIT\u堆栈,&rl))!=0){
fprintf(stderr,“getrlimit result=%d,errno=%d\n”,res,errno);
返回res;
}
如果(rl.rlim_cur>=堆栈大小)返回res;
rl.rlim_cur=堆栈大小;
如果((res=setrlimit(RLIMIT_堆栈,&rl))!=0){
fprintf(stderr,“setrlimit result=%d,errno=%d\n”,res,errno);
}
返回res;
}
静态int func(void){
国际阵列1[10000000];
int n=阵列1的大小;
printf(“%d\n”,n);
返回0;
}
内部主(空){
固定尺寸(48*1024*1024);
func();
返回0;
}
好的,谢谢,但是我有没有办法声明一个10000000大小的数组?@Jackddddd,更新了答案,如答案所示,在函数之间,写“static”(因此仅在此文件中可见)“array1[10000000];”堆栈通常只有几兆字节,您根本无法在其上放置38 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;
}