proper semantics for returning a character string?

Robert P. J. Day rpjday at mindspring.com
Thu Apr 20 16:08:57 UTC 2006


On Thu, 20 Apr 2006, Jason Schoon wrote:

> On 4/20/06, 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?
> >
> >   is that what other BB routines do?

> You have a nice potential for memory leakage using this approach.
> If this is a routine called numerous times without exiting the
> application, you will slowly be losing all that dynamically
> allocated space.  At the same time though, it is rather annoying to
> have to keep track of the fact that the pointer needs to be freed.
> It's possible, but I think people tend to err on the simple side and
> just wait for memory to be cleaned up at exit.
>
> Because of all of this, I prefer to have to pass in my own buffer
> for the function to use.  However, to program safely you then have
> to either incur the cost of passing another variable indicating the
> length of that buffer, or you have have some magic MAX define that
> both the function and caller use.
>
> I lean toward passing a buffer and length, but it may not make sense
> in Busybox where applets are generally small and run quickly, then
> exit. Answering your other question, I think there's a wide mix of
> the two methods in existing code.

i was already aware of the pros and cons of the two approaches, that's
why i asked.   i wondered whether there was already a BB standard for
this sort of thing, but i guess the answer is, "it depends." :-)

rday



More information about the busybox mailing list