Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I identify an invalid memory address?

Tags:

c

linux

memory

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.

like image 538
debamitro Avatar asked Sep 15 '14 06:09

debamitro


2 Answers

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.

like image 79
Rudy Velthuis Avatar answered Oct 04 '22 01:10

Rudy Velthuis


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

like image 26
egur Avatar answered Oct 04 '22 00:10

egur