4 ms·
So who actually checks return values of malloc, and why? (or why not?)
by thedjinn 10y ago
So who actually checks return values of malloc, and why? (or why not?)
- Retr0spectrum 10y agoIMHO checking the return value is only useful if you can actually do something about it. For example, you might want to gracefully write a database to disk before terminating the program. It's definitely bad practice, but if you run out of memory during the initialisation of a program, quitting with a segfault is a fairly reasonable error. Of course, catching the error and printing something meaningful would be much better, but if you're in a rush to get something to work for a personal project it's not much of an issue.
- thedjinn 10y agoThe article states that malloc only fails when you run out of virtual address space, which is basically never going to happen if you're on a 64 bit architecture. So you can go for good practice and check all your mallocs for failure, but if the failure never happens why bother?
- bluejekyll 10y agoAlternatively you could throw in a wait/loop and then the program would recover if memory becomes available. Though, that might never happen...
- loeg 10y agoAgreed. The more expected case would be: your httpd is already handling XXX million clients, but the next one comes in and you fail to malloc a tracking structure. Closing the connection and dropping the one client makes more sense than aborting the daemon and dropping all clients.
- loeg 10y agoChecking the return value of malloc makes sense in non-overcommit systems. And non-overcommit makes sense for reliable systems.
- Spivak 10y agoI check them in all of my code because if memory allocation fails I would rather look at recovery options or terminate the program myself gracefully then let the program keep running, performing potentially dangerous operations with bad data, until it fails somewhere down the line. Sure, maybe that code branch will never get executed but I'll immediately know if it ever does and won't have to try and figure out where the null pointer came from.