Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

assert ( malloc...

Name: Anonymous 2010-06-28 13:36

A question for you, Anon.

If you watch at malloc() manpage you can notice that the function may return NULL in some cases (i.e. errors or 0-sized allocation). How do you face this issue?

I noticed that many programmers check the return value and manage error routines for it, while other just assert() the return value not to be NULL.

Also in C++ by the way you use the new operator without taking care about the return value (I guess it's asserted to be not NULL under the hood, is it?)

What is your opinion?

Name: Anonymous 2010-06-28 17:38

>>1
Most people just don't bother checking. This is especially common in C++ where people disable exceptions (so new has no way to signal failure). In my opinion this is a terrible way to program. It's fine for desktop where you have swap and a shitload of memory, but it's completely wrong for embedded.

The way to do it correctly is that any operation that could fail should return a flag that says whether it failed, and the caller should always check this flag. If the caller is unable to handle it, it should also return an error code, and so on until someone in the call stack is able to handle it (usually by notifying the user that the operation failed.)

This does take some work to do, but it's not a huge amount; it's not nearly so bad as people pretend it is. Personally I think most developers sing the praises of exceptions because they are lazy; they think exceptions allow them to write no error handling code. In my experience writing everything with RAII and smart pointers is far more difficult, time consuming and error prone than simply returning and checking error codes.

It's also possible to test it rigorously; see e.g. how SQLite tests random malloc failures: http://www.sqlite.org/malloc.html , section 2.0.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List