1

For the life of me I can't fiqure out why nothrow isn't working. I've tried different headers. Also interchanged the the new and memory headers and still the same output:

0x61ff50    6422400
How many numbers would you like to type: 1000000000

terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length

Any ideas on what I'm doing wrong? I'm looking for a way to give a nothrow without the program crashing and using an arbitrary value for array size. Seems I have to use an array within the max size, which will bring stability to the program and thus I'm not able to test out the nothrow object; leaving me the only option of using the exception.

#include <iostream>
#include <memory> 
#include <new>    // also either/or this 


using namespace std ;

int main ()
{
    int i, n ;

    int *p ;

    cout << p << "    " << *p << endl ;


    cout << "How many numbers would you like to type: " ;

    cin >> i ;


    p = new (nothrow) int[i] ;

    if (!p)
    {
        cout << "Error: memory could not be allocated" ;
    }

    else
    {
        for (n = 0 ; n < i ; n ++)
        {
            cout << "Enter number: " ;

            cin >> p[n] ;
        }
        cout << endl << p << endl << *p << endl ;
        cout << "You have entered: " ;

        for (n = 0 ; n < i ; n++ )
            cout << p[n] << ", " ;


        delete[] p ;

        cout << endl << p << "   " << *(p + 0) << endl ;

        p = nullptr ;

        cout << endl << p << endl ;

        p = &i ;

        cout << endl << p << "    " << *p ;

    }

    cin.get() ;

    return 0 ;
}
Mr SnowGlobe
  • 57
  • 1
  • 8
  • 3
    There is a difference between memory not being allocated due to lack of memory, and memory not being allocated due to you providing an invalid parameter. The `nothrow` is for the former, not the latter. – PaulMcKenzie Apr 26 '20 at 16:37
  • @PaulMcKenzie Ok that makes sense. So I can trust that the code I have in there now will work if the time comes that memory isn't able to be allocated and the loop will run? It just makes me uneasy assuming something like the above code will work without testing it first is all. – Mr SnowGlobe Apr 27 '20 at 16:06
  • If the parameters are valid, then a thrown exception is due to lack of memory. But be careful, since a lack of memory can render a program helpless, even to the point where the memory exception isn't thrown (your program just crashes or hangs). Hopefully the environment has reserved memory on the side so that if an out-of-memory condition occurs, the program can proceed with the throwing of the exception. – PaulMcKenzie Apr 27 '20 at 16:08

0 Answers0