What is sizeof(&X) expression equal to, X being defined as "char *X[n];"?

Andrey Karpov
Articles: 565

Consider the following sample.

char *(X[64]);
cout << sizeof(&X) << endl;

The question is: what value will be printed? The right answer is "the pointer's size". In particular, it may be number 4 in a Win32 program or 8 in a Win64 program.

The answer above seems obvious, yet there are two subtleties which often cause confusion. Let's examine another sample:

char *(X[64]);
memset(&X, 0, sizeof(&X));

This code is incorrect: we empty only a part of the X array. There are two reasons for such errors.

Reason one

The VS 2005 compiler has an error that causes "sizeof(&X)" to return the array's size. As a result, this code, being built in VS 2005, will correctly empty the whole array. Accordingly, some programmers get misled and consider this code correct. The compiler's error disappears after installing SP1.

By the way, here you are an interesting test on the subject I encountered in the code of Google C++ Mocking Framework:

class TestForSP1 {
private: // GCC complains if x_ is used by sizeof before defining it.
  static char x_[100];
  // VS 2005 RTM incorrectly reports sizeof(&x) as 100, and that value
  // is used to trigger 'invalid negative array size' error. If you
  // see this error, upgrade to VS 2005 SP1 since Google Mock will not
  // compile in VS 2005 RTM.
  static char 
      sizeof(&x_) != 100 ? 1 : -1];

Reason two

The first function's argument is "&X". Actually taking of the address is not necessary here. We are handling the array all the same. That is, the following two records have the same correct result:

memset(&X, 0, sizeof(X));
memset(X, 0, sizeof(X));

This also confuses programmers and they think that sizeof(&X) and sizeof(X) will have the same result too. But it is a mistake.

Use PVS-Studio to search for bugs in C, C++, C# and Java

We offer you to check your project code with PVS-Studio. Just one bug found in the project will show you the benefits of the static code analysis methodology better than a dozen of the articles.

goto PVS-Studio;

Andrey Karpov
Articles: 565

Bugs Found

Checked Projects
Collected Errors
14 526
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →