tags:

views:

116

answers:

3

What is the best way to handle an output struct with some strings in it ?

struct info 
{ 
wchar_t * text; 
size_t text_len; 
}

void Foo(struct info * output);
  • User need to allocate text himself

    output can be recycled in a loop
    hard to know how much memory needs to be allocated, possible waste of memory if output is to be stored (eg. keeping a list a items)

  • allocate the text within Foo

    a pain for the user to free output, since he has to free each text before (can make a FreeStructInfo to ease the pain)
    not so good within loops

  • allocate output from within Foo

    Foo can embed text within struct info and user need only free output to free all.
    good for storage (Foo knows how much it needs to allocate),
    but maybe a lot of stress for memory if used as a shortlived variable in a loop since it can't be recycled.

Windows uses the "User need to allocate text himself" and either you allocate enough or you need to call the function twice to get the size needed.

+3  A: 

There's no one best way - all the options you propose are used at some time or another. The important thing is to document it well, and keep it consistent across all functions in a library, where practical.

bdonlan
+1  A: 

You could use the first idiom (user allocates) and if the space for the string is not sufficient you reallocate. This will work if you and the user agree to use the same allocation (like malloc/free). This will give you optimum performance (no allocation for every iteration) and is still convenient for the user.

With this idiom the allocated storage grows as needed, but the user can at any time choose to "shrink" it by reallocating a smaller storage (which will start growing again if necessary).

lothar
Beware specifying the initialization required on the first call (probably both length and pointer zero, but document the requirement).
Jonathan Leffler
A: 

lothar summed pretty well advantages for first idiom -- quite probably it's the best for general solutions.

However, there are times when 3rd option (modified) is better -- if you have a lot to output. To avoid memory stress you can add pools to the mix.