Search code examples
memoryglibc

Random memory address


I'm working on a virtual machine under Debian with EGLIBC 2.13 in order to learn memory address. So I wrote a simple code giving me the address of a test variable, but everytime I exec this script, I'm getting a totally different address.

Here's two screens from 2 distincts executions :

enter image description here

enter image description here

What's causing this ? The fact I'm working on a VM or my GLIBC version ? I guess it's GLIBC to prevent buffer overflow but I can't find my answer on the web. And is it totally random ?


Solution

  • First, Glib (from GTK) is not GNU libc (a.k.a. glibc)

    Then, you are observing the effect of ASLR (address space layout randomization). Don't try to disable it on a server directly connected to the Internet, it is a valuable security measure.

    ASLR is mostly provided by the Linux kernel (e.g. when handing mmap(2) without MAP_FIXED, as most implementations of malloc do, and probably also at execve(2) time for the initial stack). Changing your libc (e.g. to musl-libc) won't disable it.

    You could disable system-wide ASLR on a laptop (or on a Linux system running inside some VM) using proc(5): run

    echo 0 > /proc/sys/kernel/randomize_va_space
    

    as root. Be careful, by doing that you are decreasing the security of your system.

    I don't know what you call totally random, but ASLR is random enough. IIRC, (but I might be wrong) the middle 32 bits of the 64-bits address (assuming a 64 bits Linux system) are quite random, to the point of making result of mmap (hence of malloc using it) practically unpredictable and non-reproducible.

    BTW, to see ASLR in practice, try several times (with ASLR enabled) the following command

     cat /proc/self/maps
    

    this command displays a textual representation of the address space (in virtual memory) of the process running that cat command. You'll see different outputs when you run it several times !

    For debugging memory leaks, use valgrind. With a recent GCC 4.9 or better (or recent Clang/LLVM) compiler, the address sanitizer is also useful, so you could compile with gcc then -Wall -Wextra to get all the warnings even the extra ones, then -g to get debug info, then -fsanitize=address