<html><head><style>body{font-family:Helvetica,Arial;font-size:13px}</style></head><body style="word-wrap:break-word;line-break:after-white-space"><div id="bloop_customfont" style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto">I was just reading Roman Cheplyaka’s very interesting blog-post here: <a href="https://ro-che.info/articles/2018-02-03-stableptr-undefined-behavior">https://ro-che.info/articles/2018-02-03-stableptr-undefined-behavior</a>.</div><div id="bloop_customfont" style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto"><br></div><div id="bloop_customfont" style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto">As he points out, the docs for `freeStablePtr` say</div><div id="bloop_customfont" style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto"><br></div><div id="bloop_customfont" style="margin:0px"><span style="color:rgb(0,0,0);font-family:Helvetica,Arial;font-size:13px">"</span>if the stable pointer is passed to deRefStablePtr or freeStablePtr, the behaviour is undefined.”</div><div id="bloop_customfont" style="margin:0px"><br></div><div id="bloop_customfont" style="margin:0px">And indeed we can observe weird behavior as a result of sucn an error.</div><div id="bloop_customfont" style="margin:0px"><br></div><div id="bloop_customfont" style="margin:0px">A deRef of a stable pointer is arguably the sort of sharp-edge we know how to code to avoid. But a double free is a bit trickier. Would it be worth adding a bit more overhead to make such an operation idempotent?</div><div id="bloop_customfont" style="margin:0px"><br></div><div id="bloop_customfont" style="margin:0px">Additionally, would it be worthwhile to add `withStablePtr` to the `Foreign.StablePtr` module? I imagine there are cases that it won’t cover, but it would at least encourage good discipline in the cases that it does handle. The evident utility of such a function is witnessed by its existence in a few different codebases, not least the Win32 library (<a href="https://hackage.haskell.org/package/Win32-2.6.2.0/docs/System-Win32-Types.html#v:withStablePtr">https://hackage.haskell.org/package/Win32-2.6.2.0/docs/System-Win32-Types.html#v:withStablePtr</a>)</div><div id="bloop_customfont" style="margin:0px"><br></div><div id="bloop_customfont" style="margin:0px">Cheers,</div><div id="bloop_customfont" style="margin:0px">Gershom</div></body></html>