Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 938
Наталья Шашок Avatar asked Oct 31 '25 20:10

Наталья Шашок


1 Answers

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());
}
like image 117
Christian Hackl Avatar answered Nov 03 '25 12:11

Christian Hackl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!