简体   繁体   中英

Memory Layout of Linux (malloc() used in C, but does not start with the expected address)

I used this chunk of code:

    int
main(int argc, char *argv[])
{
    int *p;                   // memory for pointer is on "stack"
    p = malloc(sizeof(int));  // malloc'd memory is on "heap"
    assert(p != NULL);
    printf("(pid:%d) addr of p:        %llx\n", (int) getpid(), 
       (unsigned long long) &p);
    printf("(pid:%d) addr stored in p: %llx\n", (int) getpid(), 
       (unsigned long long) p);
    return 0;
}

However, I get:

addr of p:        7ffc0c53e3e0
addr stored in p: 558ae195c260

Now, first of all, since the program only does this, I do not understand why malloc() does not start with the address 00200000 ? Second, can I say that the 7ffc0c53e3e0 address is in heap , and the address 558ae195c260 is in stack ? Third, if my guess with 00200000 is wrong, is there any logic with the addresses that I get, or is it completely random?

When I think about it, the address is not even 32 bits, it is 48 bits. Even if it is to be more than 32 bits (I have 8 GB memory, so I believe it must be more than 32 anyways), why is it not expressed in 64 bits, since the processor is 64 bits.

Thank you for your help.

No, p is in stack (or global) and it points to a bunch of memory in the heap.

Regarding malloc() , if you are working on an OS, it depends on the kernel, and how it is managing the memory.

Finally, obviously some of your data is wrong. A 32bit bus data cannot manage 8GB of RAM (no more than 2^32=4GB). However, it makes sense in a 64bits bus, because a 64bits variable has enough space to contain an 8GB address.

Linux implements ASLR , so as far as I'm aware you always get random addresses. 558ae195c260 is actually allocated on the heap via malloc() , whereas 7ffc0c53e3e0 is allocated on the stack when you declare int *p; . 48 bits is still enough for 256 TB of RAM, but beyond that some architectures don't allow all address lines to be a full 64 bits (like AMD64).

Hope that helps. If anything I've said is wrong or misleading please correct me in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM