Is my version an error or just not the recommended style? I may be
wrong, but the two versions seem equivalent.
mystruct* pm = (mystruct*)malloc(sizeof(mystruct));
compare to:
mystruct* pm = malloc (sizeof *pm);
The two are equivalent, but most people consider your version to
be more error prone, and poor style, for a number of reasons:
- casting the return value from malloc() may hide a bug if
you forget to include the correct header file to declare
malloc(). In this case, the compiler is required to give
you a diagnostic if there is no cast. Many compilers will
give you a warning even if you do have the cast, but there
is no guarantee that they will and you may need to switch
on a particular warning level.
- using <sizeof *pm> makes the code more self-adjusting in
case of change. Suppose you want to change the type of this
storage area to <herstruct>. In your version, you need to
remember to change the type in two places (three if you keep
the cast), and failing to do so will result in a silent bug
that may cause buffer overruns. In the widely preferred
version, you change the type in one place and everything
else adjusts automatically.
- casting the return value from malloc() is simply not necessary.
Having unnecessary stuff in the code makes it harder to
maintain, and more prone to error during maintenance. When I
see your version, I have to work out what the cast is doing
and why it is there. This wastes my time, and makes it more
likely that I will misinterpret what the code does simply
because there is more code for me to interpret.
- it takes more typing for no benefit.
I accept the second version if this is standard, but it gives me an
uneasy feeling of being a circular argument.
Don't be uneasy - that's what's good about it! Everything on
the line that depends on the type of the object depends on the
same mention of the type.
I based my version on
the string version which I have seen in print I think:
char* str = (char*)malloc(sizeof(char))
In that case, I would throw away that bit of print. There are an
awful lot of bad books on C, and even more bad advice on the net.
I was just wondering if my version is incorrect and will cause errors,
because so far it is working ok.
It's correct and will not of itself cause errors as it stands. It
might hide another error (omit the declaration of malloc() and
you'll end up with a run-time error in some 64-bit environments,
for example). It is more prone to error if ever you modify it.
I will of course, for clarity of my
code and compliance with standard practices, change to the accepted
version regardless.
Very wise!