如何增加数组的限制? [英] How to increase limit of array?

查看:88
本文介绍了如何增加数组的限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// 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

when I change the array limit to any 8 or more digit numbers like 11111111, 68297907 (and so on...) then the program gets complied but on output it shows Segmention Error.

如何增加数组限制?我正在使用基于UNIX的系统。

How can I increase array limit? I am using a UNIX based system.

推荐答案

char buf[11111111];

这超过11兆字节。它分配在堆栈上。堆栈具有有限的大小,通常为8或10兆字节。堆栈溢出,如果超过该限制,通常会导致 segfault

This is over 11 megabytes. It's allocated on the stack. The stack has a finite size, often 8 or 10 megabytes. You're getting a stack overflow, which normally results in a segfault if you exceed that limit.

您可以:


  • 增加堆栈限制,如果您的系统支持它。您没有告诉我们您使用的是哪种系统。通常这是通过外壳完成的。对于bash,请运行例如

  • Increase the stack limit, if your system supports it. You don't tell us what kind of system you're on. This is normally done through the shell. For bash, run e.g.

ulimit -s 12000

将最大堆栈大小设置为12000千字节(120兆字节)。管理员可能设置了一个限制,以防止您使用过多的堆栈空间。您必须在运行上述 ulimit 命令的同一外壳中运行程序。

to set the max stack size to 12000 kilobytes (120 megabytes). There might be a limit set by an administrator that prevents you from using this much stack space. You must run your program in the same shell as you ran the above ulimit command.

动态分配内存:

char *buf = malloc(11111111);


  • 在堆栈之外的其他地方分配空间:

  • Allocate the space somewhere else besides the stack:

    static char buf[11111111];
    


  • 我会问是否允许某人但是在一行上输入了11 MB的数据。

    I would question the need for allowing someone to input 11 megabytes of data on one line though.

    这篇关于如何增加数组的限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆