Std bad alloc что это

от admin

How to deal with bad_alloc in C++?

There is a method called foo that sometimes returns the following error:

Is there a way that I can use a try — catch block to stop this error from terminating my program (all I want to do is return -1 )?

If so, what is the syntax for it?

How else can I deal with bad_alloc in C++?

7 Answers 7

In general you cannot, and should not try, to respond to this error. bad_alloc indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.

Worse, modern operating systems often over-allocate: on such systems, malloc and new can return a valid pointer even if there is not enough free memory left – std::bad_alloc will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).

The only thing you could do when catching std::bad_alloc is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).

In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:

    , i.e. it signals failure upon allocation rather than later.
  1. The application must be able to free memory immediately, without any further accidental allocations in the meantime.

It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change. 1

OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:

Читать:
24lc64 как считать память

But even here, using std::set_new_handler instead of handling std::bad_alloc provides the same benefit and would be much simpler.

1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.

std::bad_alloc (3) — Linux Man Pages

Constructs new bad_alloc object with an implementation-defined null-terminated byte string which is accessible through what().

Parameters

Exceptions

(none) (until C++11)
noexcept specification: (since C++11)
noexcept

bad_alloc& operator=( const bad_alloc& other );

Assigns the contents of other.

Parameters

other — another exception object to assign

Return value

Exceptions

(none) (until C++11)
noexcept specification: (since C++11)
noexcept

virtual const char* what() const;

Returns the explanatory string.

Parameters

Return value

Pointer to a null-terminated string with explanatory information.

Exceptions

(none) (until C++11)
noexcept specification: (since C++11)
noexcept

Inherited from std::exception

Member functions

destructor destroys the exception object
(virtual public member function of std::exception)
[virtual]

what returns an explanatory string
(virtual public member function of std::exception)
[virtual]

Example

int main()
<
try <
while (true) <
new int[100000000ul];
>
> catch (const std::bad_alloc& e) <
std::cout << "Allocation failed: " << e.what() << ‘\n’;
>
>

Possible output:

Allocation failed: std::bad_alloc

See also

allocation functions
operator_new (function)
operator_new[]

Обработка ошибок при выделение памяти с помощью new в C++

Есть два способа определить выделена ли память оператором new .

Способ 1. Обработка исключения

Если память не выделена, то бросается исключение std::bad_alloc .

Пример обработки исключения.

Способ 2. Проверка указателя

При вызове new в качестве аргумента можно использовать константу std::nothrow . Тогда, исключение std::bad_alloc не испускается, а вместо него возвращается нулевой указатель.

C++ Exception Library — bad_alloc

This is an exception thrown on failure allocating memory.

Declaration

Following is the declaration for std::bad_alloc.

Parameters

Return Value

Exceptions

No-throw guarantee − no members throw exceptions.

Example

In below example for std::bad_alloc.

Annual Membership

Enjoy unlimited access on 5500+ Hand Picked Quality Video Courses

Training for a Team

Affordable solution to train a team and make them project ready.

© Copyright 2023. All Rights Reserved.

We make use of First and third party cookies to improve our user experience. By using this website, you agree with our Cookies Policy. Agree Learn more

Похожие статьи