Hacker News new | ask | show | jobs
by pksadiq 3038 days ago
> To be fair, the way malloc is used is actually the preferred way.

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.

2 comments

I am not referring to the lack of null check. Just the fact that it uses `malloc(sizeof(*x))` instead of using `malloc(sizeof(Type))`.
The latter creates Heisenbugs if you change the type of x and don't track down every malloc to update the type. It is better to avoid using sizeof(typename) if possible.

Now the profligate use of leading underscores. That is an issue.

> 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.

Good point about the type change risk. However, in this case that was obviously not the reason, since there is an explicit cast (although the compiler would prevent it from becoming a HB). His hand was forced by the pointer hiding in the typedef. As I see it, this code is half-way smart, which is worse than no-way smart. (KISS!)
where's the difference if you put in the numbers by hand? Which numbers do you put in to avoid mentioning the size of the type?
You just feed sizeof the instance of the object you're allocating memory for. That entails funky pseudo-dereferences for pointers so the compiler doesn't give you the size of a pointer. It will look up the object's type and requisite size to fill in the argument to malloc(). If the object in question has an unknown type (maybe all you've got is a void *) then you will have to provide the size by other means.
Malloc does not fail under Linux unless you are in very peculiar circumstances.
Not everyone is running Linux.

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.)

Malloc will still fail for overly large allocation sizes. If you try to malloc(-1), for example.