how to cause bad_alloc

I have to cause bad_alloc for my unit test (basically, for 100% code coverage, there's no way i can change some functions). What should I do?
Here is my code example. I have to cause bad_alloc somewhere here.

bool insert(const Value& v) {
    Value * new_value;
    try {
        new_value = new Value;
    }
    catch (std::bad_alloc& ba){
        std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
        return false;
    }
    //...
    //working with new_value
    //...
    return true;
};

Upvotes: 3

Views: 3700

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27538

You can exploit the possibility of overloading class-specific operator new:

#include <stdexcept>
#include <iostream>

#define TESTING

#ifdef TESTING
struct ThrowingBadAlloc
{
    static void* operator new(std::size_t sz)
    {
        throw std::bad_alloc();
    }
};
#endif

struct Value
#ifdef TESTING
 : ThrowingBadAlloc
#endif
{
};

bool insert(const Value& v) {
    Value * new_value;
    try {
        new_value = new Value;
    }
    catch (std::bad_alloc& ba){
        std::cerr << "bad_alloc caught: " << ba.what() << std::endl;
        return false;
    }
    //...
    //working with new_value
    //...
    return true;
};

int main()
{
    insert(Value());
}

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 117926

You can just explicitly throw a std::bad_alloc in your unit test. For example

#include <iostream>
#include <new>

void test_throw()
{
    throw std::bad_alloc();
}

int main()
{
    try
    {
        test_throw();
    }
    catch (std::bad_alloc& ba)
    {
        std::cout << "caught";
    }
}

Upvotes: 0

Related Questions