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

Andrey Karpov
Articles: 330



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 
  Google_Mock_requires_Visual_Studio_2005_SP1_or_later_to_compile_[
      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++, and C# code

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: 330


Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show