I am running this program. As per my understanding, there should be a bad allocation exception raised within the try block and should cause a runtime failure. However, the program executes without any problem. I have the following questions:
Why is there no run-time error?
How does the control reach catch block even when no exceptions were thrown?
#include <iostream> using namespace std; int main() { int b =4, *c = NULL, i=-1; try{ c = new int [i]; b--; }catch (exception& e){ cout << "coming here" << endl; c = new int[1]; b++; } cout << b << endl; return 0; }
-1
will be converted to the std::size_t
value std::numeric_limits<std::size_t>::max()
due to the implicit conversion to an unsigned type. It is indeed unlikely that you have that much memory available.
However a std::bad_alloc
might not be thrown if your operating system doesn't actually allocate the memory until you consume it (common on linux platforms).
Your c = new int [i]
within the try block throws the exception because it cannot allocate the memory (i=-1), so the catch block will be executed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.