How to handle distribution of lines in an output structure

What's the best way to handle the output structure with some lines in it?

struct info 
{ 
wchar_t * text; 
size_t text_len; 
}

void Foo(struct info * output);

      

  • The user must select the text himself.

    the output can be recycled in a loop
    difficult to know how much memory needs to be allocated, possible memory loss if the output needs to be saved (e.g. saving a list of items)

  • highlight text inside Foo

    pain for the user for free output as he has to free each text before (can do FreeStructInfo to ease the pain)
    not so well inside loops

  • extract output from Foo

    Foo can insert text into structure information, and the user only needs free output to free everyone.
    good for storage (Foo knows how much to allocate),
    but maybe a lot of memory stress if used as a short-lived variable in a loop as it can't be recycled.

Windows uses "User must select text by himself" and either you select enough or you need to call the function twice to get the size you want.

0


source to share


3 answers


There is no better way - all the options you suggest are used at some point. The important thing is to document it well and keep it consistent across all functions in the library where practical.



+3


source


You can use the first idiom (user allocates) and if there is not enough space for the line, you reallocate. This will work if you and the user agree to use the same allocation (e.g. malloc / free). This will give you optimal performance (no allocation per iteration) and still user friendly.



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

+1


source


lothar promised very good advantages for the first idiom - probably the best option for general solutions.

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

0


source







All Articles