Follow-up Comment #2, bug #17846 (project freeciv):

Oops. Now I come to look at it, I think I misunderstood, and the memory leaks
I mentioned don't exist (but I may have added some myself since).

There's actually a valid alternative pattern of use of astring that's used in
some places, including the client/text.c ones I mentioned.

Suppose you declare a _static_ struct astring in a function returning  const
char * . In that case, the malloc'd storage will be re-used next time your
function is called, rather than lost; you can release the caller from the
burden of freeing the returned string, in return for 'leaking' one string over
the lifetime of the program. This is the moral equivalent of the "static char
buf[128]" type strategy that astring (probably) replaced, except that the
memory tied up in  'static' astrings is in principle unbounded (although in
practice probably not).

In that case, you definitely *don't* want your caller to be able to free() or
realloc() the memory, as that will cause the static astring to become
inconsistent and cause havoc next time your function is called. So 'const char
*' is an appropriate return type; if the caller wants to mess with the string,
they will have to take a copy (which isn't always *strictly* necessary, but
close enough).

This pattern and the one I proposed can't really coexist. Since this one is
incumbent, probably what should happen is that it should be commented more
explicitly, and a check done that everyone's using astring in a compatible
manner (which probably means reworking some code I've written while
misunderstanding this).


Reply to this item at:


  Message sent via/by Gna!

Freeciv-dev mailing list

Reply via email to