Functions using malloc (style)

The Grey Wolf greywolf at unisoft.UUCP
Fri Jun 28 17:07:38 AEST 1991


/* <2864543c.3e48 at polyslo.CalPoly.EDU> by sslee at polyslo.CalPoly.EDU (Steven Lee)
 * 
 * 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.
 *

I usually use #1 below, as I think that if the user requires some
information, (s)he should have a place to put it.

 * 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.)

see above.

 * 2. The function mallocs space each time it is called.  It is up to
 *    the user to free (release) the memory.

This is a drag -- you might as well use #1.

 * 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.
 *

Are you trying to read the ENTIRE passwd file into a structure using
getpwent(), or are you just going through, entry by entry?

If you're just going through, entry by entry, you can save your breath.
getpwent() returns a static pointer (one whose location never changes);
the manual page even advocates that if you want to save the data you need
to copy it to someplace else, as the next call to getpwent() will overwrite
the data it just got.

If you're trying to read the ENTIRE passwd file into a structure,
save yourself some crazy work and allocate an array of struct passwds.

 * Steven Lee


-- 
# "Religion is a weapon invented by the sheep to keep the wolves in line."
# greywolf at unisoft.com



More information about the Comp.lang.c mailing list