Hacker News new | ask | show | jobs
by isaachier 2870 days ago
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))`.
1 comments

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.