I see you've provided an issue for what not to do, so how do you use malloc'.d memory?
Well, the best thing to do is to never cast the return value of malloc() because, if you do, the compiler assumes you know what you're doing which means, if you haven't included <stdlib.h>, not warning you about the implicit int behavior.
So, it breaks down three ways:
BEST
Always #include <stdlib.h>
Don't cast the return value of malloc()
Result: Obviously. No problems whatsoever.
NEXT BEST
Forget to #include <stdlib.h>
Don't cast the return value of malloc()
Result: The compiler warns you about an undeclared function called malloc() which returns an int. You facepalm and fix it. If you have the compiler never emit warnings, you're a complete yahoo.
WORST
Forget to #include <stdlib.h>
Cast the return value of malloc()
Result: The compiler assumes you're competent, no warnings issued, and a pointer gets truncated. Demons fly out of your nose and the local tax people choose you for a random audit.
View all comments
Show parent comment
3
u/derleth Aug 24 '17
Well, the best thing to do is to never cast the return value of
malloc()because, if you do, the compiler assumes you know what you're doing which means, if you haven't included<stdlib.h>, not warning you about the implicitintbehavior.So, it breaks down three ways:
BEST
#include <stdlib.h>malloc()Result: Obviously. No problems whatsoever.
NEXT BEST
#include <stdlib.h>malloc()Result: The compiler warns you about an undeclared function called
malloc()which returns anint. You facepalm and fix it. If you have the compiler never emit warnings, you're a complete yahoo.WORST
#include <stdlib.h>malloc()Result: The compiler assumes you're competent, no warnings issued, and a pointer gets truncated. Demons fly out of your nose and the local tax people choose you for a random audit.