Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!spool.mu.edu!uunet!unisoft!greywolf From: greywolf@unisoft.UUCP (The Grey Wolf) Newsgroups: comp.lang.c Subject: Re: Functions using malloc (style) Message-ID: <3545@unisoft.UUCP> Date: 28 Jun 91 07:07:38 GMT References: <2864543c.3e48@polyslo.CalPoly.EDU> Reply-To: greywolf@unisoft.UUCP (The Grey Wolf) Distribution: na Organization: Foo Bar and Grill Lines: 49 /* <2864543c.3e48@polyslo.CalPoly.EDU> by sslee@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@unisoft.com