Today,I noticed a bunch of code that Instantiate a struct like below while ServiceMsg is a struct.
ServiceMsg *msg = (ServiceMsg *)malloc(sizeof * msg);
I have never seen malloc can be used like this. Can anyone explain this to me??? size of buffer is often assigned like this malloc(sizeof(int) * n) as is known to me..
There's a few details that might make it confusing:
The sizeof
operator can be used in two ways: either with parenthesis sizeof(type)
, but then the argument must be a type like int
. Or without parenthesis sizeof expr
, then the argument can be an expression. But of course an expression can contain a parenthesis in itself...
In your case sizeof *msg
takes the size of the expression *msg
, which means de-reference the pointer msg
(it's not the multiplication operator!) so we end up with a "lvalue" temporary variable of type ServiceMsg
. Which has the size of a ServiceMsg
.
Normally, de-referencing a pointer variable at the same line it is declared would be a big no-no, it is not initialized and is not yet pointing at any sensible location. The catch is that the sizeof
operator does not actually evaluate (execute) its operand, so the expression *msg
is never executed and de-referencing never happens.
This is why the code works. This style is often even recommended, since you don't have to worry about what type the pointer is pointing at - it's always type* ptr = malloc(sizeof *ptr);
regardless of what you are allocating.
The cast to (ServiceMsg*)
in your code is superfluous.