Is it safe to use cerr when working with bad_alloc?

Is it possible to use std::cerr like this?

 try { Something(); } catch(std::bad_alloc) { cerr << "Out of memory!"; } 

Does it use dynamic memory? If it fails, will it throw an exception or just not output anything?

+5
source share
2 answers

Simple case

There is one unfortunate big highlight - perhaps due to a programmer error -

 int main() { try { std::size_t bytesToAllocate; std::cin >> bytesToAllocate; std::unique_ptr<char> ptr { new char[bytesToAllocate - 1] }; // ops, if user enters 0 or extraction fails we get // std::numeric_limits<std::size_t>::max() -1 bytes to allocate } catch (const std::bad_alloc& e) { std::cerr << "Failed to allocate memory.\n"; } } 

Here, even if new fails, we definitely have more memory, because it has not been used before.

Realistic case

If, for some vague reason, the insertion of characters failed, the internal failbit turned on, i.e. setstate(std::ios_base::failbit) and, if exception set for failbit , an exception is thrown. Moreover, if an exception is badbit during insertion, badbit set badbit and if exception is set to badbit , the exception is returned.

However, AFAIK, it remains open and, therefore, is it not specified whether such an operation allocates memory or not, and how it is done. Your program may be killed due to out-of-memory protection and, thus, not being able to catch an exception if the entire process of distributing exceptions is possible at all in this state.

+1
source

the standard (27.7.3.6, p. 1057) defines some requirements for formatted output functions in streams:

Each formatted output function begins execution by constructing an object of the watchry class . If this object returns true when converting to a value of type bool, the function attempts to generate the requested result. If the generation fails, then the formatted output function executes setstate (ios_base :: failbit) , which may throw an exception . If an exception is thrown during output, ios :: badbit turns on 328 in * this error condition. If (exceptions () & badbit)! = 0 , then the exception will be thrown. . Whether an exception is thrown, the guard object is destroyed before exiting the formatted output function. If an exception is not thrown, the result of the formatted output function is * this.

(Emphasis mine)

To build a guard object (as with any object), the program will need more memory. Whether static or dynamic memory is left unspecified. In addition, as Black's response is beautifully expressed, the standard determines that an exception can be thrown when failbit is turned on.

+1
source

Source: https://habr.com/ru/post/1231961/


All Articles