Just an idea because you were talking about performance.
Note that you already have extra logic to call free.
```d
malloc
memcpy
if (stack != stackbuf)
    free
```