7 ms·
> 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 mi
by pksadiq 8y 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.
- orbifold 8y agoMalloc does not fail under Linux unless you are in very peculiar circumstances.
- jcranmer 8y agoMalloc will still fail for overly large allocation sizes. If you try to malloc(-1), for example.
- krylon 8y agoNot 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.)
- isaachier 8y agoI am not referring to the lack of null check. Just the fact that it uses `malloc(sizeof(*x))` instead of using `malloc(sizeof(Type))`.
- kevin_thibedeau 8y agoThe 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.
- posterboy 8y agowhere'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?
- kevin_thibedeau 8y agoYou 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.
- kieckerjan 8y agoGood 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!)
- saagarjha 8y ago> 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.