On Wed Nov 23, 2005 at 09:53:10 +1100, Robert Collins wrote: >On Tue, 2005-11-22 at 18:29 +1100, Benno wrote: >> ... However >> once you alloc then the interface becomes subtly differnt because the >> client must free() or else leave a memory leak. Which is bad for any long >> running >> process. >> >> And of course if somefunction() has to return some error code, not just the >> string you also need to get more trickier with pointers, and end up with >> what I had before. >> >> *but*, having any interface where you allocate data inside a function and >> expect to free is elsewhere is genreally bad, because it is too >> easy to screw up, and forget the free, probably better to supply a buffer >> if possible (with a length of course). Of course that means having some >> expection >> of the size required in the first place. > >Which (taken to extremes) leads to the terrible interface that the MS >DCE-RPC calls use all over the place, where you have N network round >trips to find out that you needed a 55K buffer not a 30K buffer, or >equally, a round trip to find that out and then a round trip to populate >it. > >... > >And the buffer you supply is itself allocated (unless you know the >length a-priori), so it must be freed too. I think allocating something >in a function and having it freed by the caller is fine as long as it is >clearly documented.
Yeah, now the cool thing is that tools like splint actually let you define and track such semantics. Basically it lets you annotate a function saything the return value is data that must be freed by the client, and can detect whether the cller drops a reference to that pointer before freeing it.... which is why way back when, I advocated that people should these tools when using C. (That said, if you don't start with itat the beginning of the project, siwtching to it mid project can be a major PITA -- but it can also find a lot of bugs you wouldn't find in testing.) Benno -- SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/ Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html
