How do you prevent variable-length arrays from crashing when there is not enough memory?

前端 未结 3 1977
萌比男神i
萌比男神i 2021-01-11 23:34

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          


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-11 23:59

    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;
    }
    

    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.

    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).

提交回复
热议问题