[fpc-pascal] Validate heap/stack addresses

Jonas Maebe jonas.maebe at elis.ugent.be
Tue Dec 1 18:27:05 CET 2009


On 01 Dec 2009, at 17:58, Bruce Bauman wrote:

> Is there a way I can tell if an arbitrary address is within the heap or
> stack?
> 
> I want to do something like:
> 
> Assert(ValidHeapAddress(a))

That is not possible without installing your own memory manager that tracks all allocations. Also keep in mind that this will never work for memory allocated by code outside your application (in some external library).

heaptrc has a function with similar functionality called checkpointer(), but
a) it's not exported
b) it checks for more than just heap allocations (it also checks for global data and stack)
c) it only works on some targets (the ones supported by -gc in 2.4.0 -- earlier FPC versions did not contain any checks regarding supported targets for this feature, so it just caused crashes on some platforms) and has not been maintained for ages (so I have no idea as to what its status is).

> Assert(ValidStackAddress(a))

This can be done by checking whether the address is <= sptr and >= stackbottom.

> to catch potential errors in the code.

If you are working on an Intel Linux or Mac OS X/i386 10.5.x platform, I would strongly recommend Valgrind.

> I'm guessing any address between "end" and the current brk is a valid
> heap address.

That is only true on some old systems (such as go32v2, and possibly some very old Linux FPC versions). In most systems, the heap is no longer a contiguous region.


Jonas


More information about the fpc-pascal mailing list