Talk:C dynamic memory allocation/Archive 1: Difference between revisions

Content deleted Content added
manually archive from the talk page
 
Legobot (talk | contribs)
m Bot: Fixing lint errors, replacing obsolete HTML tags: <tt> (5x)
 
Line 43:
Although I agree that the discussion is irrelevent to this article, just as a point of interest it is true that most sources now discourage from casting the result of malloc, and from casting void * in general. Doing so is a hang over from Ye Olden Days which is now unnecessary, doesn't serve any good purpose, and can conceal compiler warnings. [[User:NicM|NicM]] 20:14, 19 March 2006 (UTC).
 
:I agree that casting from <ttcode>void *</ttcode> is unnecessary, but I'm not sure there's a consensus on whether it is good style, and I definitely don't think that it is "strongly discouraged". It can actually produce some useful compiler warnings; for example:
 
T *foo = malloc(sizeof T);
 
If we change the type of <ttcode>foo</ttcode> but don't update the call to <ttcode>malloc</ttcode>, the code will be buggy. One way to fix this is to use <ttcode>malloc(sizeof *foo)</ttcode>, although I know a lot of people who find that construct unintuitive. Another way is to use an explicit cast:
 
T *foo = (T *) malloc(sizeof T);
 
which ensures that the programmer needs to update the RHS of the assignment if the type of the LHS changes. Now, I can't say I personally find this all that convincing (I would use <ttcode>sizeof *var</ttcode> myself), but that's the argument I've heard for casting away from void pointers in the Postgres source, for example. [[User:Neilc|Neilc]]
::I think that sounds like a fairly horrible reason to use casts. And it still hides the case where stdlib.h is omitted. As you mention, the most reliable way to solve the malloc part of the type-changes-but-programmer-didn't-check-initialisation problem is to use (sizeof *p). [[User:NicM|NicM]] 08:43, 20 March 2006 (UTC).
::In any case, a few trivial Google searches show that the vast majority of people do discourage casting malloc. Some people do cast it for various reasons, but they do seem to be a minority. Not terribly scientific, but there you go. [[User:NicM|NicM]] 08:53, 20 March 2006 (UTC).