[antlr-interest] Are C++ STL instances safe to use with the C runtime?
Gavin Lambert
antlr at mirality.co.nz
Wed Feb 11 23:06:07 PST 2009
At 12:38 12/02/2009, Richard Lewis wrote:
>Hi, I just started the process of determining how to convert my
>JAVA runtime based grammar into the C runtime. Will I run into
>memory allocation issues if I embed STL? For example, in my
>current grammar I use:
[...]
>If I translate this to:
>
>scope RScope {
> std::string name;
> std::map<std::string, int> symbols;
>}
>
>Is this even going to compile? And if it does, will it blow up or
>leak memory?
IIRC from a related discussion last week, this will indeed blow up
unless (as Jim suggested) you make these into pointers and call
new/delete at the appropriate points. (Or you leave it as is and
use placement new and explicit destruction; but those are just
weird-looking.)
This is because the default initialisation of the scope structures
just calls malloc, which won't invoke any constructors (and the
free at cleanup time won't call destructors).
Jim: maybe it'd be useful to put the definition of ANTLR3_MALLOC,
ANTLR3_CALLOC, and ANTLR3_FREE into an #ifdef __cplusplus block,
so that if the parser is being compiled as C++ it'll invoke
new/delete instead of malloc/free. (Though some care might be
needed if arrays of parser-definable structures are ever
allocated.) That ought to automatically make the use of C++ types
within scopes "safe", at least as far as construction/destruction
goes.
Or possibly (to limit the blast radius) rather than changing those
three macros directly the templates for the scope code could be
changed to call different macros that call malloc/new as
appropriate. (Something similar should be done for the rule
return structures, too.)
Of course, none of this is exception-safe, which does complicate
the use of C++ types, since most will assume that they can throw
exceptions with impunity. It seems probable that any thrown
exceptions would lead to a memory leak somewhere.
More information about the antlr-interest
mailing list