tags:

views:

795

answers:

4

I frequently encounter some definitions for Win32API structures (but not limited to it) that have a cbSize member as in the following example.

typedef struct _TEST {
    int cbSize;
    // other members follow
} TEST, *PTEST;

And then we use it like this:

TEST t = { sizeof(TEST) };
...

or

TEST t;
t.cbSize = sizeof(TEST);
...

My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the cbSize member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you.

What is the purpose of the cbSize member in some C++ structures on Win32API?

+6  A: 

My initial guess is that this could potentially be used for versioning.

That's one reason. I think it's the more usual one.

Another is for structures that have variable length data.

I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.

Michael Burr
A: 

Partially versioning, mostly safety... to prevent the called function from poking into memory that wasn't part of the struct passed in.

Hafthor
+7  A: 

It is used for versioning. A good example is the GetVersionEx call. You can pass in either an OSVERSIONINFO or OSVERSIONINFOEX. The OSVERSIONINFOEX is a superset of OSVERSIONINFO, and the only way the OS knows which you have passed in is by the dwOSVersionInfoSize member.

Rob Walker
Stucts vary in size between OS versions as well. I just hit a bug using the platform sdk that comes with VC++ 2008. We were not correctly defining the OS version and ended up using the Vista version of a struct - which didn't work so well on my XP box.
Aardvark
+2  A: 

It also lets the WIN32 API do a minimal amount of sanity checking on the data being passed in.

For example a commom mistake is for a WIN32 structure to be passed in with an incorrect or uninitialised cbSize and when this happens the WIN32 API usually just returns a failed result, rather than try to process what appears to be corrupted data.

jussij