How should sizeof be used in malloc()'s argument?

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:

Last updated 05 Jan 2004 12:25. Copyright © 2004 Ben Pfaff.
May be freely redistributed, but copyright notice must be retained.