Casting Allocation In C
If I allocate block of memory for the
obj_t it’s look like this
After reading this post, I’m wondering why I use cast anyway?
My thought was because
malloc and friends is returning
void * so I need to cast to the appropriate type.
And now if I ask myself “Why do you need to cast anyway? Is there any effect?”. My answer was “I don’t know”. So I decide to doing some research about this.
I found this StackOverflow answer which provide excellent information about the bad of using cast for
malloc and friends.
This is a quick summary from that discusion
Do I cast the result of malloc?
It’s turnout that
cast is a harmful, I should avoid them as much as possible.
Is there any effect using cast?
Well, 100% Agree.
The last one
“It’s better to dereference the pointer being used to store the return value”
I don’t cast allocation anymore and use dereference the pointer instead of type name as an argument of
The good news is it also improve my code to be more readable.