by isaachier · 8y ago · 0 comments
However, I'm surprised the author did not point out that they are calling malloc() without checking for a NULL return value.
Why?
To quote malloc(3):
On error, these functions return NULL. NULL may also be returned by a
successful call to malloc() with a size of zero, or by a successful call to
calloc() with nmemb or size equal to zero.
I'm not disagreeing with your assertion that on linux, in practice, it doesn't return NULL -- (in fact, I didn't know that! and would appreciate being pointed at whatever I need to RTFM...) -- I just prefer code that's conservative, that follows the "letter of the law" when it comes to return values.This is only true on Linux, and isn't even guaranteed there. I'm pretty sure the default overcommit handling mode is still to refuse allocations that are much larger than there is free memory to support. (This was the case around 2.6.)
It's generally preferable for software to check if malloc() failed and have a chance to recover.
> Checking the return of malloc() for NULL is not currently considered good practice
This is simply false. I was a TA for the intro C class at CMU last year, and we still teach to check for NULL. In fact, we mark down students who do not do so.
This way hey are calling malloc() is very common in professional code bases and a safety measure; I’m surprised the author was surprised.
I am not used to that style so it seems odd to me, but I suppose if it was common in a codebase one would get used to it.
It's confusing for readers and new team members. And can even lead to strange when someone forgets to type "struct".
So why would that be "the preferred way"? I've been writing C for some time and no one who knows C casts the return value of malloc.
Also, the fact that they cast the result of malloc makes me think they were using a C++ compiler, which will complain that there's no cast.
Ah ok, makes more sense in re-reading now. I was lazy and went off of a child comment.
>Also, the fact that they cast the result of malloc makes me think they were using a C++ compiler, which will complain that there's no cast.
Definitely could be that.
Is it really right? In C, isn't it considered bad to cast malloc result as it masks some mistakes? Also, the code doesn't check for NULL for the malloc result.
Now the profligate use of leading underscores. That is an issue.
This is a pretty common way of shoehorning access control into languages that do support them natively.
And anyway, it is dirty - like crossing the street without looking for cars because traffic around here is very mellow, or peeing without washing your hands afterwards.
(That being said, I once helped somebody to write a program whose task it was to deliberately get the host system to the point where malloc(3) failed. It was not as trivial as one might think.)