[ale] C memory management basic question.

Alexander Barton abarton at mindspring.com
Thu Nov 1 17:20:14 EST 2001


Christopher Fowler wrote:
> 
> I am begining to write some fuctions that replace <pwd.h> functions.
> 
> one will be struct uentry *(char *name).  The function will take a name and
> return a pointer
> to a uentry structure
> 
> struct
> uentry *(char *name)
> {
>         struct uentry *uuser;
> 
>         uentry = (struct uentry *)malloc(1);  //Allocate space for one;
> 
>         /* .. Do some stuff  get the correct user */
> 
>         return *uuser;
> }
> 
> When this function terminates, will the memory allocated for uuser in the
> function be reaped?

It's hard to say what the above code will do since it's incorrect and
probably won't even compile.  (Hint: you're not allocating enough space;
you're not freeing the allocated space; and your return statement
doesn't match your function's declared  return type.)

My kneejerk reaction is to say: don't use C.  C is bad because to do
anything useful one must often have to play with pointers and dynamic
allocation and do other really low-level stuff.  Pointers are so easy to
screw up it's not funny.  I'd say use C++ instead.  You can do most
things in C++ without ever having to even think about a pointer of
allocate memory manually.  (Container classes, string classes,
references.)

If you must use C, and if you don't have to stay signature-compatible
with the old function, I'd get rid of the dynamic memory and use
something more straight forward like this:

void my_getpwnam(const char *name, struct uentry *entptr)
{
	struct uentry newent;

	/* Get your user info into newent.  */

	*entptr = newent;
}
 

> Thanks,
> Chris

-- 
Alexander Barton         "...Unix doesn't have a monopoly on good ideas,
abarton at mindspring.com    it just owns most of them." -Alan Cox

---
This message has been sent through the ALE general discussion list.
See http://www.ale.org/mailing-lists.shtml for more info. Problems should be 
sent to listmaster at ale dot org.






More information about the Ale mailing list