// C Program to find average of numbers given by user
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
double sum = 0;
int ii = 0,c;
char buf[256], *token;
printf("Enter the numbers to average on a single line, separated by space and press enter when done\n");
fgets(buf, 255, stdin);
token = strtok(buf, " ");
while (token != NULL)
{
sum += atof(token);
ii++;
token = strtok(NULL, " "); //Get next number
}
printf("Average is %lf", sum / (double)ii);
}
第 8 行:
char buf[256], *token;
当我将数组限制更改为任何 8 位或更多位数,如 11111111、68297907(等等...)时,程序会得到编译,但在输出时显示 Segmention Error
.
如何增加数组限制?我使用的是基于 UNIX 的系统。
最佳答案
char buf[11111111];
这超过 11 兆字节。它是在堆栈上分配的。堆栈的大小是有限的,通常为 8 或 10 兆字节。您遇到了堆栈溢出,通常会导致 segfault如果您超过该限制。
你可以:
增加堆栈限制(如果您的系统支持)。您没有告诉我们您使用的是哪种系统。这通常是通过 shell 完成的。对于 bash,运行例如
ulimit -s 12000
将最大堆栈大小设置为 12000 KB(120 兆字节)。管理员可能设置了限制,阻止您使用这么多的堆栈空间。您必须在运行上述
ulimit
命令的同一个 shell 中运行您的程序。动态分配内存:
char *buf = malloc(11111111);
在堆栈之外的其他地方分配空间:
static char buf[11111111];
不过,我质疑是否需要允许某人在一行上输入 11 兆字节的数据。
关于c - 如何增加数组的限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19269985/