Re: Test if memory pointer is valid?
- From: Rob Kennedy <me3@xxxxxxxxxxx>
- Date: Thu, 26 Jan 2006 22:08:15 -0600
Richard A. DeVenezia wrote:
Is there a way or technique for knowing if a pointer points to memory that has been freed ?
Yes. When you free it, remember that fact so you don't use the variable anymore.
The example is a little silly, in reality, P & Q might fields in instances of disparate classes
P: Pointer; Q: Pointer; BuffSize: Integer;
BuffSize := 32000; GetMem(P, BuffSize); F.Read(P^,BuffSize); ... Q := P; ... if ... FreeMem(P,BuffSize) ...
if [ Q points to memory that has not been freed ] // what technique, if any, can test this? FreeMem (Q,BuffSize);
Keep track of who owns the memory. You have two references to it, but only one of them "owns" it. Only allow the owner to free it. If assigning P to Q also bestows ownership, then don't free the memory through P. Only free it through Q.
The other way is to let everyone be an owner, and when the memory stops being owned by anyone, free it. This involved counting the references to the memory. When you assign P to Q, the reference count needs to go up.
Given an arbitrary address, it is not possible to know whether you're allowed to call FreeMem on that address. Consider this:
GetMem(P, 20); Q := P; FreeMem(P); GetMem(R, 20);
After those four lines run, it's quite likely that Q = R, so if there were such a function as IsValidPointer, then IsValidPointer(Q) would return True even though Q doesn't refer to the same thing you initialized it to. Freeing the memory via Q would succeed, but it would invalidate R's value.
The solution to all this? Write you program in such a way that you never need to make these sorts of checks in the first place. Keep strict tabs on who owns the memory.
-- Rob .
- References:
- Test if memory pointer is valid?
- From: Richard A. DeVenezia
- Test if memory pointer is valid?
- Prev by Date: Test if memory pointer is valid?
- Next by Date: Re: DBGrid1.OnDrawColumnCell goes into infinite loop
- Previous by thread: Test if memory pointer is valid?
- Next by thread: Re: Test if memory pointer is valid?
- Index(es):
Relevant Pages
|