I have got some codes written in C, it returns an array allocated using 'calloc'. However, as far as I know, we need to do the 'free'. But if we free the array before return, it will return nothing. If we don't do free, we will get a memory leak somehow in the future. May I ask how to do it please? Here is the codes:
Rbt* mcrbt_CreeRbtVide(int32_t taillemax, void *lpBuffer, size_t *lpBuffSize)
{
//Calculate the required buffer size. If it is less than *lpBuffSize, don't perform the operation
//and return in *lpBuffSize the required size.
size_t requiredSize = sizeof(Rbt) + taillemax * sizeof(RbtElt);
if (*lpBuffSize < requiredSize)
{
*lpBuffSize = requiredSize;
return NULL;
}
//At this point, all you have to do is cast the lpBuffer pointer as (Rbt*) and you are good to go.
.....
}
//Callers of the function are then required to provide their own buffers, like this:
size_t buffSize = 0;
void *lpBuffer = NULL;
mcrbt_CreeRbtVide(someValue, lpBuffer, &buffSize);
lpBuffer = malloc(buffSize);
//Now the buffer is ready and good to go. Repeat the function call.
mcrbt_CreeRbtVide(someValue, lpBuffer, &buffSize);
//Use the data
....
//Now release the buffer.
free(lpBuffer);
This is my favorite choice because the caller is free to use whatever memory allocator function he/she requires, like Windows' HeapAlloc(), or COM's IMalloc, etc.