Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To be able to pass arbitrary pointer values to that function, you need to follow the same model as FreeAndNil and pass in an <strong>untyped parameter</strong>. Otherwise, the compiler correctly complains about actual and formal parameter types not being identical. Type-cast the untyped parameter to Pointer when you call FreeMem on it.</p> <p>You're doing a couple of pointless things in that function.</p> <p>First of all is that freeing a nil pointer is always safe, so there's no reason to check for that before calling FreeMem. It's freeing a non-nil pointer that you need to worry about, but no function can protect you from that.</p> <p>Next, the size parameter to FreeMem has been ignored for many years. It used to be that if you provided that parameter, it needed to match the size passed to GetMem, but nowadays, FreeMem completely ignores that parameter — the compiler doesn't even pass that parameter to the function.</p> <p>With all of the above in mind, your function boils down to this:</p> <pre><code>procedure FreeMemAndNil(var P); var Tmp: Pointer; begin Tmp := Pointer(P); Pointer(P) := nil; FreeMem(Tmp); end; </code></pre> <p>Be careful not to accidentally call that function on anything that <em>isn't</em> a pointer allocated with GetMem. The compiler won't catch it for you like it could if you were using typed parameters. If you attempt to free something that wasn't allocated with GetMem, you'll probably get an EInvalidPointer exception, but the variable you passed in will still be nil afterward. That's the same way FreeAndNil works.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload