Functions using malloc (style)

Steven Lee sslee at polyslo.CalPoly.EDU
Sun Jun 23 17:56:44 AEST 1991


When you write a C function and it returns a pointer to some
structure, how should the function do this?  Many of the system
functions I know create a static area that gets rewritten when
the user makes multiple calls to it.  This avoids the problem
of allocating memory each time the function is called.

The possible solutions I have come up with are:
1. Force the user to malloc his own space and then call the function.
   I personally don't like this idea because the user should not have
   to worry about this. (User is defined to be the programmer using
   the particular function.)
2. The function mallocs space each time it is called.  It is up to
   the user to free (release) the memory.
3. Use the static technique as described above, however it will not
   work if a VARIABLE structure (one you don't know the size of)
   needs to be returned (ie say you need to return a pointer to a
   string but you don't know how long the string may be).
   a. Malloc a large enough memory so the structure is bound to fit.
      This would waste a lot of memory and it still may crash for
      unusual situations, so I don't like this idea.
   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.


What I need to do is read the /etc/passwd file using the getpwent()
function.  I want to store all the information in a structure and return
a pointer back to the callee.  However, I don't want this structure
in memory more than once if it is called multiple times.

Steven Lee



More information about the Comp.lang.c mailing list