Re: Reporting malloc failure in actions

Akim Demaille <[email protected]> Wed, 30 Dec 2020 07:48:18 +0100
Newsgroups gmane.comp.parsers.bison.general
Message-ID <[email protected]>
Hi Joe,

> Le 29 déc. 2020 à 05:37, Joe Nelson <[email protected]> a écrit :
> 
> Hi, is there a recommended way to fail parsing when an action cannot
> allocate memory? I could use YYABORT, but the caller could mistake this
> for a problem in the input, when it's really an internal problem.

I never though about that.

> Looking at the generated foo.tab.c file for my parser, I see these
> macros:
> 
> 	#define YYACCEPT        goto yyacceptlab
> 	#define YYABORT         goto yyabortlab
> 	#define YYERROR         goto yyerrorlab
> 
> Later in the file I see an interesting label that has no corresponding
> documented macro:
> 
> 	/*-------------------------------------------------.
> 	| yyexhaustedlab -- memory exhaustion comes here.  |
> 	`-------------------------------------------------*/
> 	yyexhaustedlab:
> 	  yyerror (scanner, callback, YY_("memory exhausted"));
> 	  yyresult = 2;
> 	  goto yyreturn;
> 
> This seems to be exactly the code I should execute, since it would
> inform the caller what went wrong. One option would be for my code to do
> something like this:
> 
> 	if (!(bla = malloc(n)))
> 		goto yyexhaustedlab;
> 
> I don't like relying on undocumented internals like this, since they're
> subject to change across versions of Bison. Any advice?

I guess most people just fail here, and don't even try to recover from
memory exhaustion.  Out of curiosity: do you really manage to keep your
program working after you've run out of memory?

I don't think this area (yyexhaustedlab) would change, but you are right
it is an internal detail.  I'll add something public in the future,
maybe YYNOMEM.  Any idea of a good spelling for such a macro?
YYEXHAUSTED doesn't sound right.