I have a Visual Studio 2008 C++ Windows Mobile 6 application where I'm using a FindFirst() / FindNext() style API to get a collection of items. I do not know how many items will be in the list ahead of time. So, I would like to dynamically allocate an array for these items.
Normally, I would use a std::vector<>
, but, for other reasons, that's not an option for this application. So, I'm using LocalAlloc()
and LocalReAlloc()
.
What I'm not clear on is if this memory should be marked fixed or moveable. The application runs fine either way. I'm just wondering what's 'correct'.
int count = 0;
INFO_STRUCT* info = ( INFO_STRUCT* )LocalAlloc( LHND, sizeof( INFO_STRUCT ) );
while( S_OK == GetInfo( &info[ count ] )
{
++count;
info = ( INFO_STRUCT* )LocalRealloc( info, sizeof( INFO_STRUCT ) * ( count + 1 ), LHND );
}
if( count > 0 )
{
// use the data in some interesting way...
}
LocalFree( info );
Thanks, PaulH
Edit: Responders are (not unreasonably) getting hung up on the use of LocalAlloc() over other better options. So I will provide more context.
This chunk of code is being executed from within a RAPI invokable DLL. So, in that context, it looks more like this:
FOO_API int RapiInvokable_Foo( DWORD /*cbInput*/,
BYTE* /*pInput*/,
DWORD* pcbOutput,
BYTE** ppOutput,
IRAPIStream* /*pStream*/ )
{
int count = 0;
INFO_STRUCT* info = ( INFO_STRUCT* )LocalAlloc( LPTR, sizeof( INFO_STRUCT ) );
while( S_OK == GetInfo( &info[ count ] )
{
++count;
info = ( INFO_STRUCT* )LocalRealloc( info, sizeof( INFO_STRUCT ) * ( count + 1 ), LHND );
}
*ppOutput = ( BYTE* )info;
*pcbOutput = sizeof( INFO_STRUCT ) * ( count + 1 );
return S_OK;
}
From the CeRapiInvoke() documentation:
An application should allocate memory for the pInput parameter with the LocalAlloc function. The caller is responsible for freeing pInput. The system allocates memory for the ppOutput parameter. When the application is completed with the buffer, it should free the memory with the LocalFree function.