[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [PATCH] Don't cast the return of malloc() and friends
From: |
Hussam al-Homsi |
Subject: |
Re: [PATCH] Don't cast the return of malloc() and friends |
Date: |
Tue, 1 Sep 2020 17:32:34 -0400 |
>> Subject: [PATCH] Don't cast the return of malloc() and friends
>> Because doing so is superfluous.
>
> It may be redundant, but does it do any harm?
Other than wasting some space, it can do harm if one forgets to include
<stdlib.h> and older C compilers then suppose a return of int and trigger the
wrong conversion from int to a pointer type.
> Also, if ever the type of one of the relevant variables is changed, the
> cast will cause compilation errors -- without the cast the compilation
> would silently but probably wrongly succeed.
The conversion from void*, the return type of malloc(), to the target type is
automatic and doesn't need any intervention.
Now about changes to target types. That would only be a problem if the argument
of malloc() references the target type:
T* p = malloc(sizeof (T));
For that problem I suggest using this idiom instead:
T* p = malloc(sizeof *p);
Where the type info is specified only once.
But that's for another time. :)
Thanks.
Hussam
- Re: [PATCH] Don't cast the return of malloc() and friends,
Hussam al-Homsi <=