[antlr-interest] How to free ANTLR3_STRING (c runtime)?

Jim Idle jimi at temporal-wave.com
Fri May 15 10:53:30 PDT 2009


Chetty, Jay wrote:
> What's the right way to free the ANTLR3_STRING returned from
> pANTLR3TOKEN_STREAM's toStringSS()
>
>
> I used destroy method of the string factory and it seems that's not the right way
> As I get these lines when my executable exists.
>
> *** glibc detected *** double free or corruption (fasttop): 0x081514b8 ***
> *** glibc detected *** double free or corruption (!prev): 0x081641a8 ***
>   
The correct way is to do nothing at all:-). The string factory tracks 
the memory and releases it once you close the factory. The factory will 
be created by the token or node stream and will be closed when you free 
the token or node stream.

Note that the string factory stuff is basically convenience methods for 
things like toStringTree(). If you need pure performance, then you 
should access the token structures yourself.

You can use valgrind to check that all your memory is being freed correctly.

Also note that while making a string from the AST is a quick way of 
looking at your tree, you might find the dot generator and the dot 
program much more useful (install graphviz from your distro or 
www.graphviz.org).

To use it from C, you just do this:

pANTLR3_STRING    dotSpec;
dotSpec = nodes->adaptor->makeDot(nodes->adaptor, psrReturn.tree);

Where nodes is the pANTLR3_COMMON_TREE_NODE_STREAM and psrReturn is the 
return type of the rule you invoke on your parser.

You can then fwrite the spec to a text file:

dotSpec = dotSpec->toUTF8(dotSpec);   // Only need this if your input 
was not 8 bit characters
fwrite((const void *) dotSpec->chars, 1, (size_t) dotSpec->len, dotFILE);

Then turn this in to a neat png graphic like this:

sprintf(command, "dot -Tpng -o%spng %sdot", dotFname, dotFname);
system(command)

Jim


More information about the antlr-interest mailing list