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. |
One Response to “C++ and the bad_alloc exception”
Leave a Reply
Quote: “Calling [] on a vector apparently returns *(begin() + offset), which when the offset is larger than the size points to invalid memory.”
And that yields undefined behaviour, which means that anything can happen, including a bad_alloc exception being thrown. This is no way to “invoke that behaviour”, and it does not contradict the standard either. It’s simply a blunt mistake that should not happen, just like dereferencing a NULL pointer.