0

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"?

  • It's ok to use `malloc`/`free` and `new`/`delete` in the same program, as long as you use them consistently: always `free` a `malloc`ed pointer, and always `delete` a `new`ed pointer. – BoBTFish Jul 27 '14 at 08:12
  • 1
    `__val[count]` isn't undefined if `count` is negative as long as that still points inside a valid memory block of the right type. (You don't have an array there, just a pointer to `char*`.) – Mat Jul 27 '14 at 08:15
  • @BoBTFish I know this. The code of the parser is completely isolated from other code in the program, but I still see an interference in certain conditions. I have no idea why. Anyway using array[-2] is obviously asking for trouble, but this is not my code and I have to make it work. – Semen Yesylevskyy Jul 27 '14 at 08:16
  • @Mat Yes, that's true. However I got a memory corruption at that line in certain conditions. – Semen Yesylevskyy Jul 27 '14 at 08:19
  • 1
    @Semen Yesylevskyy: that doesn't mean that that function is the culprit. Try using valgrind. – Mat Jul 27 '14 at 08:23
  • @Mat Valgrind finds a problem at that line: Conditional jump or move depends on uninitialised value(s) ... 4: yySet(_yycontext*, char*, int) ... Not sure if indicates the source of the problem. – Semen Yesylevskyy Jul 27 '14 at 08:28
  • possible duplicate of [C++ Reserve Memory Space](http://stackoverflow.com/questions/2492934/c-reserve-memory-space) – Paul Sweatte Oct 13 '14 at 22:21

0 Answers0