HOMEBLOGDEVLOG

Fix return use after free

Adam C. Clifton
7 May 2026

In my custom programming language, there is the concept of "owned" pointers, that will auto delete themselves when they go out of scope. The problem is that happens just before any return statement. So if that return statement uses the owned pointer, it accesses deleted memory and crashes confusingly a short time later.

I thought this was going to be a pretty painful problem to resolve, but it turned out pretty easy in the end. Now when we inject cleanup, if the last statement is a return we delegate cleanup to it, so it can inject a temporary variable with the result of the expression, delete, then return the temporary variable.

For the rest of the code we just continue as normal, injecting at the end of scope, or before any continue or break statement.

As an example, here was the last straw for me, in nll code we use a locally owned pQuery to get the result.

return pQuery.Execute(pConn) && LoadFromExecutedQuery(pQuery);

In C++ this became:

if (pQuery) delete pQuery;
return pQuery->Execute(pConn) && LoadFromExecutedQuery(pQuery);

Which is obviously problematic.

And now the corrected code is:

bool __nll_return_temp = pQuery->Execute(pConn) && LoadFromExecutedQuery(pQuery);
if (pQuery) delete pQuery;
return __nll_return_temp;
Previous: Fix for defaulting all function params
Next: Database improvements
© Numbat Logic Pty Ltd 2014 - 2026