Reputation: 548
I am trying to catch bad allocation error. When input length will be in order of 10000000000000000000000 or something, then bad allocation error should come. I don't know why its not being caught. Any help will be appreciated!
# include <vector>
# include <iostream>
using namespace std;
void length(int m)
{
vector<int> x;
try
{
x.resize(m);
}
catch(std::bad_alloc&)
{
cout << "caught bad alloc exception" << std::endl;
}
}
int main()
{
int l;
cout << "Length" ;
cin >> l ;
length(l);
return 0;
}
UPDATED:
When I am hard coding the value for input, then it is throwing an exception. I don't know why its working this way.
# include <vector>
# include <iostream>
using namespace std;
void length(int m)
{
vector<int> x;
try
{
x.resize(m);
}
catch(std::bad_alloc&)
{
cout << "caught bad alloc exception" << std::endl;
}
}
int main()
{
int m= 100000000000000000000;
length(m);
return 0;
}
Upvotes: 1
Views: 350
Reputation: 866
No exception is thrown because the int
that makes it through to your function void length(int m)
is capped at its max value that is much less than vector::max_size()
. Consider:
void length(int m)
{
cout << "m is: " << m << " which has a max value: " << numeric_limits<int>::max() << endl;
// ...
}
with the output:
Length10000000000000000000000
m is: 2147483647 and has a max value: 2147483647
Upvotes: 0
Reputation: 20
#include <iostream>
#include <new>
int main()
{
try {
while (true) {
new int[100000000ul];
}
} catch (const std::bad_alloc& e) {
std::cout << "Allocation failed: " << e.what() << '\n';
}
}
</i>
Upvotes: 0
Reputation: 234785
You ought to write
if (!(cin >> l)){
// I could not read that into `l`
}
The lack of an exception being caught could be down to
Your int
value being smaller than you think (perhaps some undefined wrap-around behaviour), and an exception is not thrown since the allocation is successful.
The allocation being lazy in the sense that the memory is not allocated until you actually use it.
If std::bad_alloc
is thrown as an anonymous temporary then it will not be caught at your catch site. (Unless your naughty compiler allows non-const
references to bind to anonymous temporaries, which some do as an extension). Write catch (const std::bad_alloc&)
instead, and it will be caught there.
Upvotes: 1
Reputation: 482
The maximum length of an integer type int is 2.147.483.647 . Are you sure you have actually used an higher number to test it?
Upvotes: 0