Using sizeof in a smart way

It seems that very few people comprehend how powerful C and C++’s sizeof operator really is. People insist on using sizeof on typenames. Folks, you don’t have to do that!

Typical code:

struct foo *f = malloc(sizeof(struct foo));

The way it should be written:

struct foo *f = malloc(sizeof(*f));

As you can see in the example above you can even dereference a pointer to get the correct size. What about dynamically allocating an array? That’s elegantly written like this:

int *array = malloc(sizeof(array[0]) * 44);

Using variables instead of types with sizeof is simply more robust. If you change the type of a variable you do not need to change your use of sizeof in anyway.

Generally speaking sizeof operates strictly at compile time. That means that anything that the compiler knows the size of will work with the sizeof operator. With C99 there is at least one case that I know of where sizeof is actually dynamic. In C99 you can declare “dynamic” arrays.

int dyn(int numElements) { int dynArray[ numElements]; int x = sizeof(dynArray); }

The example above will not compile in C++ and in most C compiler unless the C compiler supports C99. In the example above there is no way for the compiler to know the size of dynArray at compile time because numElements isn’t known until execution of the function. Regardless, with a C99 compliant compiler the code above will produce correct results.

So go forth and use sizeof on variable names, not on type names!

* Sorry about the crappy formatting. I’m battling the rich editor built into wordpress.

This entry was posted in Code, Geek. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s