Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do structures need to be told how big they are?

Tags:

c++

c

struct

sizeof

I've noticed that in c/c++ a lot of Win32 API structs need to be told how big they are. i.e someStruct.pbFormat = sizeof(SomeStruct)

Why is this the case? Is it just for legacy reasons? Also any idea what "pb" stands for too?

EDIT: oops, yeah I meant "cbFormat"

like image 430
GameTrainersWTF Avatar asked May 31 '10 01:05

GameTrainersWTF


1 Answers

This is for backward compatibility when Windows API is extended.

Imagine the following declarations

struct WinData
{
   long flags;
}
BOOL GetWinData(WinData * wd);

which you are calling like this:

WinData wd;
GetWinData(&wd);

A future OS version may extend this to

struct WinData
{
   long flags;
   long extraData;
}

However, if you have compiled against the "older" SDK, GetWinData has no chance to figure out you don't know about extraData. If it would fill it in regardless, it would overwrite data on the stack. BOOOM!

That's why, the "size known to the caller" is added to the structure, and new members are appended at the end. The GetWinDataimplementation can inspect the size and decide "this poor guy doesn't know about all the new features yet".

like image 128
peterchen Avatar answered Sep 25 '22 01:09

peterchen