Afficher un message
Vieux 06/02/2008, 21h21   #21
Michal Nazarewicz
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Advice on how to return a list of values

"Remo D." <rdentato> writes:

> Hi! I'm writing a function that returns an array of (at maximum) 64
> pointers to char. I have thought of three possibility:
>
> - The caller passes a pointer to a previously allocated array of 64
> pointers. Similarly to sprintf(), the caller is entirely responsible
> for handling the memory. The drawback is that my function will have to
> rely on the correctness of such pointer to work properly.


IMO it's not a drawback really. The same goes with all standard library
functions operating on strings which are free to assume that user gave
them a valid string.

>
> - My function allocates the array and returns it. This is similar to
> strdup(). Here I will have to rely on the caller function to properly
> free the array, which is something I'm not very comfortable with.
>
> - I'll have a "static char *ret[64]" in my function and will return
> ret. I've not been able to think of a library function that behaves
> this way, so I guess it's not reccomended.


There are plenty. For instance strerror() may (as far as I know) do
such a thing. strtok() is another example of function that uses static
buffer.

> The good is that I'm free
> from allocation/freeing problem. The bad is that the return values
> will be overwritten at each call; if the user wants to keep the return
> values for subsequent use he has to copy and store them somewhere.


If your function does not need to be reentrant (ie. you are not writing
a multithread application this approach is (in my opinion) not bad and
I'd choose that.

However, if function needs to be reentrant I'd choose the "sprintf()"
approach, ie. user supplies buffer.

> Another drawback is that it consumes memory even if the function will
> never be called.


Come one... 64 pointers? That's not that much.

> In my specific case, I was leaning toward the third option but
> I'd like to hear your opinion on pitfalls, things that I've missed or
> alternative approaches that could work better.


As I've said -- if you don't care about reentrant functions and
multithreading applications go ahead. But generally, I'd advice the
first option as you get reentrant function with no costs.

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--
  Réponse avec citation
 
Page generated in 0,06344 seconds with 9 queries