How to judge an address as legal or illegal by it‘s numerical value? [closed]

If you are debugging your program (compiled with gcc -Wall -g), the gdb debugger will tell you if some address is illegal. Use also valgrind and the address sanitizer of GCC 4.8 (gcc -fsanitize=address)…

If you want inside your program to know if some particular address is or not in its address space (of a process running your program) and in which segment it is, you could make a routine parsing /proc/self/maps to do that. Reading that file (or other files from proc(5) …) is really fast (since such files don’t exist on disk).

There is usually not a single text segment, or a single data segment, or a single stack segment (think of multi-threaded applications and dynamic linking) in a given process. There are several segments in your address space (the address space of a process running your program), which are usually “randomly” laid out by the kernel because of ASLR. (ASLR can be disabled system-wide)

However, if address values matter to your application at runtime (sometimes it is interesting to encode some type information in the address, i.e. to allocate pairs in one segment, triplets in another, and larger objects elsewhere), you should take the opposite approach: explicitly manage by yourself large memory segments (e.g. aligned to a megabyte) with mmap(2) and munmap(2) (which are called by posix_memalign(3)…) and when you reserve your segments, register them in appropriate containers (e.g. a std::map in C++). Then you would easily code a routine which, given some arbitrary address (any void*), gets your segment containing it (or else nullptr). Don’t forget that malloc can be internally used by many library routines (including printf and C++ standard containers…). So malloc is always used even without you knowing how. You may be interested by mallinfo(3), malloc_info(3), mallopt(3). Read also the C dynamic memory allocation & memory management wikipages, and study if needed the source code of malloc (the one inside MUSL libc is easy to read).

Consider reading Advanced Linux Programming; it should help you.

Leave a Comment