The bad_alloc C++ exception program example


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Trying and catching the bad allocation exception in C++ programming

To show: The bad_alloc C++ exception program example




// bad_alloc, first version, the allocation is OK

#include <new>

#include <iostream>

using namespace std;


int main(void)


char* ptr;

unsigned long int Test = sizeof(size_t(0)/3);

cout<<"The size of variable Test = "<<Test<<endl;



// try some allocation...

// size of an array must not exceed certain bytes

ptr = new char[size_t(0)/3];

delete[] ptr;


catch(bad_alloc &thebadallocation)






Output example:


The size of variable Test = 4

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index