
Function returns pointer to dynamic array
Quote:
> I have a function (a dll) that returns a pointer to a dyanmic array of
> structures. This routine is called again and again.
> Since the memory for the pointer is allocated inside the function, when do I
> deallocate the memory.
> Obviously, I can not delete before I leave the function.
> Does the calling program have to deallocate it, or should I attempt to
> deallocate it upon entering the function before reallocating it.
If it is in a dll, you want to make sure that the same dll is where
the memory gets deallocated. Otherwise you may mismatch memory
managers and cause serious problems.
So for example, if your function (in a dll) is called allocate_array(), it
would be VERY wise of you to create a matching function called
deallocate_array(Array *ptr).
That way a user can load your dll, obtain an allocation from your dll,
then can give it back to your dll to free when it's finished. It's
important to make symmetric interfaces.
Also, you might also consider writing a class to encapsulate the
pointer, such that its destructor will automatically call back into
the dll to free the allocation for you. This way the user is not
responsible for any memory management issues. (It's generally not a
good idea to return raw pointers to allocated memory, because it's so
easy to leak.)
--
Chris