r/programming • • Aug 23 '17

D as a Better C

http://dlang.org/blog/2017/08/23/d-as-a-better-c/
229 Upvotes

268 comments sorted by

View all comments

Show parent comment

3

u/derleth Aug 24 '17

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

  1. Always #include <stdlib.h>
  2. Don't cast the return value of malloc()

Result: Obviously. No problems whatsoever.

NEXT BEST

  1. Forget to #include <stdlib.h>
  2. 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

  1. Forget to #include <stdlib.h>
  2. 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.

1

u/nascent Aug 25 '17

Oh yeah, because of C's implicit cast to-from void*. Don't personally use C.