When calling malloc()
, I recommend applying the sizeof
operator to the object being allocated, not the type. For instance, don't write this:
int *x = malloc (128 * sizeof (int)); /* Don't do this! */
Instead, write it this way:
int *x = malloc (128 * sizeof *x);
There's a few reasons to do it this way:
If you ever change the type that
x
points to, it's not necessary to change themalloc()
call as well.This is more of a problem in a large program, but it's still convenient in a small one.
Taking the size of an object makes writing the statement less error-prone. You can verify that the
sizeof
operand is correct by verifying that it agrees with the type assigned to, without having to look at the declaration. In particular, there should be one more dereferencing level in thesizeof
operand than in the assignment.