std::vector may terminate without throwing

  c++

I wanted to test whether my program will be able to run in parallel by pre-allocating the memory I need.
I noticed that std::vector seems to call a terminate without raising an exception at the moment it should actually work.
I have no trouble if I instead use new. The program shows in both cases the same output.

// estimate maximum number of threads
auto test_alloc = [](int num_threads, const size_t num_voxels) {
    auto ta_impl = [](int num_threads, const size_t num_voxels, const auto& fcn) {
        if(num_threads < 1) {
            return 0;
        }
        constexpr int safety_margin = 1;
        volatile char *tmp = nullptr;
        try {
            const size_t n = (num_threads+safety_margin+1) * num_voxels;
            //tmp = new volatile char[n];
            volatile std::vector<uint8_t> tmp(n, 0);
        }
        catch(std::bad_alloc &ba) {
            //if(tmp) delete tmp;
            std::cerr << "Not enough memory for " << num_threads << " threads :(" << std::endl;
            return fcn(--num_threads, num_voxels, fcn);
        }
        //if(tmp) delete tmp;
        return num_threads;
    };
    return ta_impl(num_threads, num_voxels, ta_impl);
};

Output:

Not enough memory for 8 threads :(
Not enough memory for 7 threads :(
Not enough memory for 6 threads :(
Not enough memory for 5 threads :(
Not enough memory for 4 threads :(
Not enough memory for 3 threads :(

Source: Windows Questions C++

LEAVE A COMMENT