当没有足够的内存时,如何防止可变长度数组崩溃? [英] How do you prevent variable-length arrays from crashing when there is not enough memory?

查看:91
本文介绍了当没有足够的内存时,如何防止可变长度数组崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在支持可变长度数组之前,我将像这样动态分配它们:

Before variable-length arrays were supported, I would dynamically allocate them like this:

int foo(size_t n)
{
    int *arr = malloc(n * sizeof int);
    if (!arr) return ENOMEM; /* not enough memory */
    .
    . else do stuff with arr[]
    .
    free(arr);
    return 0;
}

使用可变长度数组,现在可以使它看起来更干净:

With variable-length arrays I can now make it look cleaner:

int bar(size_t n)
{
    int arr[n];
    .
    . do stuff with arr[]
    .
    return 0;
}

但是,现在我没有内存不足"检查.实际上,如果n太大,程序将崩溃.

But now I have no "out of memory" checking. In fact, the program crashes if n is too big.

如果n太大,如何从bar(n)处保释?

How can I gracefully bail from bar(n) if n is too big?

推荐答案

这种情况与任何其他局部变量完全一样-像这样的声明:

The situation is exactly unchanged from any other local variables - a declaration like this:

int baz(void)
{
    int arr[100000];
    .
    . do stuff with arr[]
    .
    return 0;
}

有完全相同的问题. 解决方案"与往常一样-不要过于深入地递归,也不要分配具有自动存储持续时间的非常大的数据结构(在这种情况下,请继续使用malloc()). 非常大"的值在很大程度上取决于您的环境.

has exactly the same problem. The "solution" is the same as it always has been - don't recurse too deeply, and don't allocate very large data structures with automatic storage duration (continue to use malloc() for these cases). The value of "very large" depends strongly upon your environment.

换句话说,除非您知道n绑定到一个合理的值,否则不要声明int array[n];,这样您将很高兴将最大大小的数组声明为普通的,不变的修改的类型数组.

In other words, don't declare int array[n]; unless you know that n is bounded to a reasonable value, such that you would have been happy to declare an array of that maximum size as an ordinary, non-variably-modified type array.

(是的,这意味着可变地修改类型的数组并不像它们初次出现时那样有用,因为仅以最大所需大小声明该数组所获得的收益就很少.)

(Yes, this means that variably-modified type arrays are not as useful as they first appear, since you gain very little over just declaring the array at the maximum needed size).

这篇关于当没有足够的内存时,如何防止可变长度数组崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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