Thursday, 10 November 2016

c++ - Using malloc() and sizeof() to create a struct on the heap

Best practices for using malloc:


struct Employee *p = malloc(sizeof *p);

You also need to fix your IDE/compiler to tell it you're writing C and not C++, since it's too broken to figure this out on its own...


Since some people seem unhappy with this answer (and with my disapproval of the other answers), I think I should explain why working around the problem is not good.


In C, casting the return value of malloc is harmful because it hides warnings if you forgot to include stdlib.h or otherwise prototype malloc. It also makes your code harder to maintain; all the answers with a cast require making 3 changes if the type of p needs to be changed, while my answer requires a change only in one place. Finally, new C programmers should not get in the bad habit of using casts whenever they see a compiler warning or error. This usually just buries bugs. Correct code almost never requires casts, and their use should be seen as a code smell

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...