proper semantics for returning a character string?

Jason Schoon floydpink at gmail.com
Thu Apr 20 14:25:58 UTC 2006


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?


I'm sure this will turn into a religious thread, with all stating their
personal preferences, so here are my thoughts ;-)

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.busybox.net/pipermail/busybox/attachments/20060420/c6b0c665/attachment-0002.htm 


More information about the busybox mailing list