Re: ptrs validity
- From: "Ancient_Hacker" <grg2@xxxxxxxxxxx>
- Date: 11 Jul 2006 06:18:45 -0700
a wrote:
Hi,
I have a pointer that points to an unknown heap memory block, is it possible
to check the pointer + 3 is valid or not?
If it is impossible, how can I do the check?
Thanks
The language-lawyers will give you the disengenuous answer "No, it's
impossible kid, go away, you bother us".
Here's ELEVEN different ways to do it:
if by "valid" you mean "inside addressable memory space" you can
(1) On Unix, set up a SEGFAULT signal handler to trap bad memory
references.
(2) On most systems that have exception handling try/catch, you can
usually catch address exceptions.
(3) On Windows, and I suspect Unix/Linux, you can ask the OS for a list
of memory segments allocated to your process, and their attributes.
Search the list to see if the desired address lands inside a readble
or writeable area.
(4) On Windows, there's a APi for this, IsBadPtr() or somesuch? Or
was this only for Win16 style segments? I forget
(5) On the x86 architecture, since the 486, there's a hardware
instruction to check this, ERRR, ERRW, ERRE to check for read write or
execute addressability of a pointer.
If your C compiler can do an _emit or _asm{} block, you can use this
for a very quick, definitive and encvapsulated answer.
(6) Most linkers emit dummy tags, something like _endBSS, _endCODE,
_endDATA, symbols you can check at run-time to see if an address falls
in a particular range.
(7) Most heap implementations expose a structure with heap info, so
you can access arena->base, arena->limit, and other interesting
heap-address revealing pointers.
(8) Keep a list of all malloc()'ed blocks, this is very useful for
checking parameters and pointers and values passed to free() and
realloc() for validity.
(9) Put all your globals in a struct, so you can check addresses
against the ends of that struct for validity.
(10) On the x86 and many other architectures, you can define malloc()
to allocate a fresh, hardware checked segment for each allocation. Then
there's a way to lookup the base and limit of each segment in the
segment tables. Foolproof and free hardware array bounds checking!
(11) Redefine malloc() to pad each heap block and all unallocated
memory before and after each block and arena and unused stack with a
run of 0xDEADBEEF. if p+3 == 0xDEADBEEF you know you're addressing
past the end of a heap block.
.
- Follow-Ups:
- Re: ptrs validity
- From: Richard Heathfield
- Re: ptrs validity
- References:
- ptrs validity
- From: a
- ptrs validity
- Prev by Date: Re: Comments are welcome for two sequential search C functions
- Next by Date: Re: Comments are welcome for two sequential search C functions
- Previous by thread: Re: ptrs validity
- Next by thread: Re: ptrs validity
- Index(es):
Relevant Pages
|