Testing a bad allocation?

I want to test some of the exception handling in my program, but it's hard to do. I will almost never have a bad allocation.

Is there a way to debug in the specific case of a bad allocation? As in, I can force a bad_alloc exception, just to see how it's handled?

1
2
3
4
5
6
try {
   int * k = new int[100];
}
catch (std::bad_alloc) {
   std::cout << "this exception was caught\n";
}
Last edited on
Try something like:

1
2
3
4
5
6
try {
   int * k = new int[((size_t)~0)];
}
catch (std::bad_alloc) {
   std::cout << "this exception was caught\n";
}


It allocates a ridiculous amount of memory that the OS probably won't/can't ever give you.
Last edited on
You could either allocate more memory than the OS will ever give you. Try allocating a few million structures containing arrays of a few milion characters. But the OS can use swapping to just give you a file (or only give you memory when you actually use the memory), so this might not work.

You could try just throwing the exception yourself. Try

 
throw std::bad_alloc();


Last edited on
closed account (E0p9LyTq)
keanedawg wrote:
I want to test some of the exception handling in my program, but it's hard to do. I will almost never have a bad allocation.

Either manually throw a bad allocation exception, or try to allocate a LOT of heap memory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

// remove the try catch block to see this application crash disgracefully
int main()
{
   try
   {
      // Request LOTS of memory space 
      unsigned short* pAge = new unsigned short[0x2fffffff]; // notice the array allocation

      // Use the allocated memory 

      delete[] pAge;
   }

   catch (std::bad_alloc)
   {
      std::cout << "Memory allocation failed. Ending program\n";
   }
}
Topic archived. No new replies allowed.