proper semantics for returning a character string?

Robert P. J. Day rpjday at mindspring.com
Thu Apr 20 19:29:06 UTC 2006


On Thu, 20 Apr 2006, Tito wrote:

> On Thursday 20 April 2006 17:47, Natanael Copa wrote:
> > On Thu, 20 Apr 2006 10:15:44 -0400 (EDT)
> > "Robert P. J. Day" <rpjday at mindspring.com> wrote:
> >
> > >
> > >   a trivial question but what would be the proper way to implement a
> > > routine that returns a character string consistent with busybox?
> > >
> > >   for example, let's say i wanted to write my routine:
> > >
> > >   char* map_uid_to_username(int uid)
> > >
> > > to return, of course, the username character string corresponding to
> > > the UID.
> > >
> > >   obviously, i want that string to persist after the function call so
> > > is the proper technique for that routine to determine the name, then
> > > malloc() just enough space to hold a copy?
> >
> > What about:
> >
>
> char *map_uid_to_username(int uid) {
>  	struct passwd *pwd;
>  	pwd = getpwuid(uid, &pwd);	<-- ????????
>  	if (pwd) return pwd->pw_name;
> 	bb_error_msg("uknown uid %d", uid);
>  	return NULL;
> }

the library routine getpwuid() does not take a second parameter, so
i'll just assume that's a typo.  the issue that was raised earlier,
though, was that if you call that routine repeatedly, even for the
same UID, you're going to slowly consume memory as every call to
getpwuid() allocates space for a new "struct passwd", right?  and that
seemed to be cause for concern.

however, if you think about doing the same thing with just regular
calls to getpwuid() as you would on a non-BB system, you're going to
have *exactly* the same problem, no?  so maybe it's not worth worrying
about the memory leak if that's the normal behaviour in the first
place.

the *other* option would be to implement map_uid_to_username() in
terms of getpwuid_r() instead, which could avoid the memory leak
issue, no?

rday



More information about the busybox mailing list