The story is the following. I'm playing with the peg/leg parser generator, which has an excellent syntax for defining PEG grammars and is extremely easy to use. I was completely happy with it until I got mysterious segfaults with generated parser. Some research revealed the problem in one of the generated helper functions:
YY_LOCAL(void) yySet(yycontext *yy,
char *text,
int count)
{ yy->__val[count]= yy->__; }
This function is always called with count<0. Using negative index on a C array is undefined behavior. As I understand the memory is allocated by peg/leg in such a way that pointing backward from array beginning gives a correct pointer in some other array. This is actually very bad code, but it works fine most of the time. However, some allocation in other parts of my program forces different places for memory chunks and everything segfaults.
I suspect the problem is caused by the fact that peg/leg uses malloc and my program uses new, but I cant change my code to use malloc and can't fix peg/leg (it's to complex and obscure).
Thus I need to isolate the memory, which is used by the parser from the rest of my program to avoid any interference.
Is there any way to do this in C++? Any possibility to put the parser code into the "sandbox"?