sizeof(buffer)

Question: What’s the size of buffer?
char* buffer;
Answer: On most mainstream systems 4 or 8 bytes, depending on the toolchain and operating system.

Question: What’s the size of buffer?
char buffer[128];
Answer: sizeof(char) * 128 which is 128, since sizeof(char) is 1 by definition.

Question: What’s the size of buffer?
char buffer[128]
Answer: On most mainstream systems 4 or 8 bytes, depending on the toolchain and operating system. What? You just said it was sizeof(char) * 128. Well, yes that’s true if it’s a global or local array. But if it’s passed as a value like this

void f(char buffer[128])
{
}

then it looks like an array but it’s in fact a pointer to char (and at least GCC 4 will allow you to pass an array of chars of any size to f without giving you a warning). So don’t just look at the declaration, you most look at the context since sometimes it changes everything.

This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

3 Responses to sizeof(buffer)

  1. akeinexile says:

    This is one of those mistakes I stumble upon from time to time even though I very well know about it.

    the function call example seem extra devious, is there any reason to declare the size of the array in the function? Will GCC detect writes that are out of range of the array?

  2. kristianr says:

    axeinexile> At least GCC will not check it anyway so it’s only giving a false sense of security.

    I don’t think GCC does such clever analysis. You should check out the LLVM/Clang project. It looks very promising, they are working on code analysis tools and they have come a really long way in just a few years. Recently they managed to compile the Linux kernel and they compile many parts of Boost.

  3. akeinexile says:

    Interesting stuff. We are currently also looking for a static code analyzer tool so it might be interesting to see what clang might offer in this aspect as well.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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