Answer the question
In order to leave comments, you need to log in
How to make std::bad_alloc exception fire?
The book devotes one page to the bad_alloc exception and gives an example like this:
typedef unsigned long ULONG;
int main()
{
setlocale(0, "");
const ULONG SIZE = 10200;
char* ptr;
try
{
ptr = new char[SIZE];
}
catch (std::bad_alloc)
{
std::cout << "\n Исключение bad_alloc: невозможно разместить данные в памяти.\n";
}
delete[] ptr;
std::cout << "\nПамять используется без сбоев.\n";
getch();
return 0;
}
Answer the question
In order to leave comments, you need to log in
#include <iostream>
#include <conio.h>
int main()
{
setlocale(LC_ALL, "Russian");
const size_t SIZE = 3000000000ul;
char* ptr = NULL;
try
{
ptr = new char[SIZE];
std::cout << "Память используется без сбоев.\n";
}
catch (std::bad_alloc&)
{
std::cout << "Исключение bad_alloc: невозможно разместить данные в памяти.\n";
}
delete[] ptr;
getch();
return 0;
}
I'll post the answers to the questions in the comments here:
Is system("pause") platform independent?Not
After all, the program immediately closes. Or is it handled in some other way?Set up the IDE normally, or run programs from the command line instead of double-clicking. This is normal and correct behavior for console programs.
Is the reference only used with std::bad_alloc or with classes too?C++ exception handling standard: throw by value, catch by reference.
That is, pointers of this type must always be initialized? If not char* ptr = new char[SIZE], then char* ptr = NULL and on the other line ptr = new char[SIZE]?If it
char* ptr = new char[SIZE]
throws an exception, then the ptr variable does not exist and there is nothing to delete. You should always initialize a variable when you declare it. What is another question. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question