May 17th, 2018

How do I create a SAL annotation for a structure with a variable-length array?

Some Windows structures end with an array of size 1. If you try to access any members of that array beyond the first, you may get a static analysis error.

typedef struct THINGGROUP
{
  DWORD NumberOfThings;
  THING Things[ANYSIZE_ARRAY];
};

void ProcessAllTheThings(_In_ const THINGGROUP* group)
{
 for (DWORD index = 0; index < group->NumberOfThings; index++) {
  // static analysis warning: possible index past end of array
  // when NumberOfThings >= 2
  ProcessOneThing(group->Things[index]);
 }
}

How do you tell the Visual Studio static analysis tool that the size of the Things array is specified by the NumberOfThings member?

You use the _Field_size_ annotation. The documentation doesn’t really give an example of this case, so here you go:

typedef struct THINGGROUP
{
  DWORD NumberOfThings;
  _Field_size_(NumberOfThings)
  THING Things[ANYSIZE_ARRAY];
};
Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.