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: 19 2010-06-29 2:40

>>28
No, on Linux it may still return a valid pointer. Your app may even work properly, since it can page to swap. It will only crash if you actually attempt to read/write to more pages than are physically available.

Apparently certain apps (e.g. sendmail) relied on this functionality. On startup it would allocate, say, a two gig chunk of scratch memory to use for internal allocations. Usually it would only use a small portion of this, so even if you only have 512 MB of ram, it would still work perfectly fine.

>>20
Yeah pretty much. This is also why I *hate* string libraries like bstring and std::string. If something malloc()s I want to damn well know about it!

Personally I'm a big fan of the rule of no allocations outside of app startup. Unfortunately this usually leads to the C programmer's disease, but if you do it right this can be managed.

This isn't really suitable for most applications though. I've often thought about how I would write something like a word processor. I think allowing malloc() strictly on startup, document load, and inputting/pasting text would be okay. In those three situations you could conceivably propagate up an allocation failure, telling the user to close some open documents to free memory. Of course you could also allocate a fixed block of memory and page in and out sections of the document as needed, so there is no reason you should need to malloc() at all.

Maybe I'm just behind the times. Everybody's wristwatch is going to have gigs of RAM soon, so why am I still bothering with this malloc() bullshit?

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