Writing
MyStruct *s = malloc(sizeof(*s));
has exactly the same effect as
MyStruct *s = malloc(sizeof(MyStruct));
except that now you only write MyStruct once. That is, the object you're allocating has its source type determined automatically, which reduces the chances of errors.
For example - it has happened to me - you start with a MyStruct
. Then you decide you need also a different MyStruct
for different purposes. So you end up with two different structures, MyStruct
and AnotherStruct
.
Then you refactor your code and change some variables from MyStruct
to AnotherStruct
, and end up with
AnotherStruct *s = malloc(sizeof(MyStruct));
which might actually work in several circumstances, or for a long time, until you make another little and, at that point, completely unrelated change in either structure. At that point your code goes kaboom.
E.g.
typedef struct {
int a;
int b;
} StructA;
typedef struct {
int a;
int b;
int c;
} StructB;
int main() {
// No problem here except wasted space
StructA *s = malloc(sizeof(StructB));
// t->c dwells in undefined country
StructB *t = malloc(sizeof(StructA));
}