Functions using malloc (style)

Barry Margolin barmar at think.com
Mon Jun 24 02:34:14 AEST 1991


In article <2864543c.3e48 at polyslo.CalPoly.EDU> sslee at polyslo.CalPoly.EDU (Steven Lee) writes:
>When you write a C function and it returns a pointer to some
>structure, how should the function do this?
...
>The possible solutions I have come up with are:
>   b. This is the best solution I have so far for a variable structure
>      that needs to be returned.  Create a static pointer and initially
>      set it to NULL.  Upon calling this function, it checks to see
>      if the pointer is NULL.  If it isn't, it first deallocates
>      the memory and then reallocates the amount needed.  This avoids
>      malloc'ing memory and never returning it back upon multiple calls.

2c. Use a static pointer, as in 2b above.  Also create a static size_t
variable that contains the current allocation size of the structure.  Only
reallocate if the amount you need is larger than the current size.

Actually, if you just use realloc() rather than free()/malloc(), a
well-implemented memory manager should do this automatically.

3. Allow the caller optionally to provide his own pointer.  Accept a
pointer input argument; if it's null, the function allocates the structure
itself and returns the pointer to it.  In either case, it's the caller's
responsibility to free it.
-- 
Barry Margolin, Thinking Machines Corp.

barmar at think.com
{uunet,harvard}!think!barmar



More information about the Comp.lang.c mailing list