How to free the memory after return the array?

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)
{
int32_t i;
Rbt * T = (Rbt *)calloc(1,sizeof(Rbt) + taillemax*sizeof(RbtElt));

T->max = taillemax;
T->util = 0;
T->maxutil = 0;
T->nil = &(T->elts[0]);
T->nil->left = T->nil->right = T->nil->parent = NULL;
T->root = T->nil;

return T;
// My question is how to free this T then?
}
Document the requirement that users of mcrbt_CreeRbtVide have ownership of the return and are responsible for the free.
Or you can opt to request the caller of the function for the appropriate buffer, like the Windows API. I prefer this method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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.
why don't just encapsulate the data and let the destructor free your memory?
Or just use smart pointer to do all of the dirty jobs?
@stereoMatching: It is C, not C++. But yes, that would be ideal. :-)
sorry, I should read the post carefully.
Topic archived. No new replies allowed.