C++ and the ‘new’ operator

Just a little one for you people out there that use C++ and are either used to the C alloc functions or have just never quite got round to reading the documentation properly 😉

The ‘new’ operator in C++ isn’t actually spec’d to return a NULL pointer if the memory allocation fails, which is unlike the C alloc functions, it instead is meant to throw a std::bad_alloc exception. Now that’s all well and good except in two situations: 1) You don’t like using exceptions (I’m afraid I fall into the “return value should tell you what you need to know” camp) or 2) Further to not liking exceptions you have in fact turned them off. In this second case you have a bit of a serious problem if you don’t know about this particular aspect of the operator as if you’ve turned exceptions off then the compiler will still generate the same code, which will happily use the invalid pointer returned by the operator when it calls the constructor, and the OS should kill your app if it’s doing its job.

You have two options at this point if you don’t wish to use exceptions. First, you can declare the operator differently and pass an extra parameter in order to force it to return NULL on a failed allocation rather than throw the exception. Alternately, you can pass GCC the -fcheck-new parameter (assuming you’re using GCC of course, though other compilers may have similar flags) and it will insert checks on the pointer before it calls the constructor (this is automatic if you use the alternate version of new, which is how it can return NULL and not kill itself).

Of course, if I wish to follow this advice myself I need to edit my code a bit, but until then my app doesn’t officially support machines that are running low on memory 😛

[Info sourced from here]

Facebooktwittergoogle_plusredditpinterestFacebooktwittergoogle_plusredditpinterest
Loading Facebook Comments ...
  1. […] going to start off by retracting something I said here. I now see how exceptions can be very nice, fun and neat compared to using return values to signal […]