I was wondering if there some way to identify an invalid memory address on a particular platform (x86 64-bit, for my case). I need it to catch a program much before it dereferences the address and throws a SIGILL/SIGSEGV error.
In general, you can't. An invalid address looks much the same as a valid one. The only invalid address that is recognizable is NULL
.
So be sure (write your code thus) that your pointers are either valid or NULL
before you use them. Always. There is no way around that.
You can use tools to detect places where your pointers may be invalid (e.g. uninitialized, already freed, etc.), but that is not what you were asking.
You can use the mincore
function. See description here.
If the address is not mapped to the process virtual address space, mincore
will return an error.
This isn't 100% as memory can be mapped to the process virtual address space but not committed (no physical pages allocated). It will catch the bulk of your garbage pointers if not all.
You can read more on memory mapping with the mmap
function in here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With