testing bad_alloc exception

Hi
I'm making a dynamic stack class based on a linked list. When making a new node in the list there is a check for bad_alloc exception:
1
2
3
4
5
6
7
8
9
10
11
12
template <class T>
void dynStack<T>::push(T value)
{
try
  {
    top = new listNode<T>(value, top);
  }
 catch (std::bad_alloc&)
   {
     std::cout << std::endl << "Error allocating memory";
   }
}

Now I wan't to test if the exception works. i tried making a ridiculous amount of stack elements, but the program died with the words "Killed" (translated from swedish), and then the computer was really funky.
So, how can I test this without messing up the whole system?
I assume you are running on linux based on the error message?

If so, run as non-root and set the user's max memory usage to
something considerably less than the amount of RAM/virtual memory
you have.

EDIT: you can't std::cout inside there, though, because very likely std::cout will
throw another bad_alloc and that will kill your program for sure.
Last edited on
Yepp, I'm running Ubuntu. But I have no idea how to set a users max RAM. A clue?

Ok, so if I cant use std::cout, how should I get notified about the exception being thrown?
Look up ulimit

Most programs balk at handling OOM exceptions exactly because there isn't much you can do.
Ok, thanks.
One possible thing to do is to add a try-catch block in main around your entire program and catch
the std::bad_alloc there. At that point, you have to make sure the rest of your program is
completely exception safe, and hope that enough memory got freed by stack unwinding and
running destructors that you can now output your message.
Topic archived. No new replies allowed.