G
G
Gina Lee2015-10-04 18:53:25
Programming
Gina Lee, 2015-10-04 18:53:25

How to provoke bad_alloc?

There is such a piece of code. How to provoke bad_alloc?

type_T * new_value;
try {
new_value = new type_T;
}
catch (std::bad_alloc& ba){
std::cerr « "bad_alloc caught: " « ba.what() « std::endl;
return false;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
MiiNiPaa, 2015-10-05
@MiiNiPaa

throw bad_alloc

A
AtomKrieg, 2015-10-04
@AtomKrieg

If you have a class, then let it try to grab a lot of memory. I did the following manipulations with your code and it worked.

try {

    size_t sz = SIZE_MAX;
    auto new_value = new int[sz];

  }
  catch (std::bad_alloc& ba){
    
    std::cout << "bad_alloc caught: " << ba.what() << std::endl;
    return false;

  }

W
werktone, 2015-10-05
@werktone

class type_T {
    int *p;
public:
    type_T() {
        p = new int[100000000000000000];
        std::cout << p[0] << std::endl;
    }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question