C++ and the bad_alloc exception
It’s interesting that although the C++ standard clearly states that a bad_alloc exception can be thrown by the new operator, there are also trickier ways to invoke that behavior. From ISO 14822 18.4.1, new and delete:
Return a non-null pointer to suitably aligned storage (basic.stc.dynamic), or else throw a bad_alloc exception. This requirement is binding on a replacement version of this function
Now, take a look at this code:
vector <string> v;
v.push_b ack(”Item One”);for(unsigned int i = 0; i < 2; i++){
string temp = v[i];
}
Although obviously wrong, it will throw a bad_alloc exception. Calling [] on a vector apparently returns *(begin() + offset), which when the offset is larger than the size points to invalid memory. When passed by copy to the string constructor, it’s then obvious how a bad_alloc exception would get thrown. However, when you’re writing c++ code and your program throws bad_alloc, it can be a little harder to work backwards. CPP is a tiresome language.
This entry was posted on Friday, July 8th, 2005 at 11:39 am and is tagged with code vector, lt 2, null pointer, v push, c standard, c code, unsigned int, storage, memory. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback.

Add New Comment
Viewing 1 Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks
(Trackback URL)