← Learn

Introduction to Windows API

Author
Moise Medici
Updated
23 Jan 2026 · Completed

Calling the same function twice or more

There are scenarios in which the same function is called twice, and often the second call is inside a loop. One example is in the Example section of the RegQueryValueExA documentation 11, reported below:

#include <windows.h>
#include <malloc.h>
#include <stdio.h>
#define TOTALBYTES 8192
#define BYTEINCREMENT 4096
void main()
{
DWORD BufferSize = TOTALBYTES;
DWORD cbData;
DWORD dwRet;
PPERF_DATA_BLOCK PerfData = (PPERF_DATA_BLOCK) malloc( BufferSize );
cbData = BufferSize;
printf("\nRetrieving the data...");
dwRet = RegQueryValueEx( HKEY_PERFORMANCE_DATA,
TEXT("Global"),
NULL,
NULL,
(LPBYTE) PerfData,
&cbData );
while( dwRet == ERROR_MORE_DATA )
{
// Get a buffer that is big enough.
BufferSize += BYTEINCREMENT;
PerfData = (PPERF_DATA_BLOCK) realloc( PerfData, BufferSize );
cbData = BufferSize;
printf(".");
dwRet = RegQueryValueEx( HKEY_PERFORMANCE_DATA,
TEXT("Global"),
NULL,
NULL,
(LPBYTE) PerfData,
&cbData );
}
if( dwRet == ERROR_SUCCESS )
printf("\n\nFinal buffer size is %d\n", BufferSize);
else printf("\nRegQueryValueEx failed (%d)\n", dwRet);
}

RegQueryValueEx is called once, but since the PerfData buffer might be too small to hold all the data stored in the registry key, it continues to be called with a bigger size every time until it succeeds inside the while loop. This is due to the fact that the size of the object being retrieved is unknown and there is no API that can give that value directly. Some APIs like EnumProcessModules specify this in their documentation:

It is a good idea to specify a large array of HMODULE values, because it is hard to predict how many modules there will be in the process at the time you call EnumProcessModules. To determine if the lphModule array is too small to hold all module handles for the process, compare the value returned in lpcbNeeded with the value specified in cb. If lpcbNeeded is greater than cb, increase the size of the array and call EnumProcessModules again.