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.
When GCC & C++ don’t play fair
When GCC and C++ don’t play fair, you get error messages like this:
MyCoolProgram.cpp: In method`void MyCoolProgram::main_thing(const Parameter *)’:
MyCoolProgram.cpp:48: No match for`Logging<one , Two, Three>::make(const std::string&, int)’
MyCoolProgram.cpp:50: switch quantity not an integer
MyCoolProgram.cpp:51: case label `”thing.test.”‘ does not reduce to an integer constant
MyCoolProgram.cpp:53: confused by earlier errors, bailing out
I really find that error message too humane for a compiler. Error messages should be terse, informative, and technical. They should have razor-edge clarity, and not contain human babble that explains if they are “confused.” Wouldn’t you rather see something like, “Error recovery failed: no possible immediate 4-substitutions allow parsing?”
Hashmap Implementation in C
Last semester I wrote a Hashmap in C from scratch, which was an interesting experience. It’s the first datastructure I wrote in C, since most of the time I’m working with java, so I learned a lot about pointers and memory allocation (malloc/free). Just uncommented the “free()” at the end I think there is one deallocation bug that I didn’t have a chance to fix, and note that it has references to “semaphores” for thread safety, but you can remove those if you’re in a single threaded environment. Anyway, the full source code is below, as well as in pdf versions:

