How do I generate an 'Out of Memory' exception for testing purposes in c++?

I tried real big arrays but the compiler came up with this:

"total size of array must not exceed 0x7fffffff bytes"

So i tried the maximum limit allowed by the compiler and still no exception generated...

For testing heap memory you can manually throw std::bad_alloc in standard C++ or System::OutOfMemoryException in C++.NET. For stack memory, calling an unconditionally recursive function will eventually overflow the stack.

This code:

#include <iostream>
#include <vector>
using namespace std;

int main()
{

#include <vector>
std::vector<double> a;

int i =0;
while(1)
{
  a.push_back(i);
  i++;
}
  
  return 0;
}

produces

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.