What Is The Std::bad_alloc Exception In C++?

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeWhat is the std::bad_alloc exception in C++?

Exceptions in C++ are run-time anomalies or abnormal conditions that a program encounters during its execution. C++ provides the following specialized keywords for exception handling:

try: represents a block of code that can throw an exception.

catch: represents a block of code that is executed when a particular exception is thrown.

Definition

std::bad_alloc is a type of exception that occurs when the new operator fails to allocate the requested space. This type of exception is thrown by the standard definitions of ​operator new (declaring a variable) and operator new[] (declaring an array) when they fail to allocate the requested storage space.

svg viewer

Code

The following code displays the error message shown when std::bad_alloc is thrown.

#include <iostream> #include <new> // Driver code int main () { try { int * myarray = new int[1000000000000]; } catch (std::bad_alloc & exception) { std::cerr << "bad_alloc detected: " << exception.what(); } return 0; } Run

Relevant Answers

Explore Courses

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved

Tag » How To Fix Bad_alloc