When I print out the address of different memory regions I get values like 0xda2280, 0x7f8a494f9010 etc. And these point to different bytes in memory.
1) But why are the ranges so large? Would each address in between have been addressable that would mean that I'd have over 140TB of memory. How do I interpret this?
2) Most of the times the addresses are grouped within high and low addresses (heap and stack). But sometimes I see three different regions, clearly separated. What is this third memory region?
/proc/<pid>/smaps to see all the different addresses ranges the process has mapped. You'll find that something like an initialized global variable has an address that corresponds to the range mapped to the executable file itself, stack variables from the stack map, and small malloced data from the heap map. The address of a function in a shared library (e.g.
&printf) will appear in that lib's text segment mapping.
There are different ways to create a mapped range, such as
brk() to change the heap size and
mmap() to map parts of the file into memory. The latter is how the code and data segments of executable and shared libraries are placed into memory.
Rather than allocate ranges one right after the other, different kinds of allocations have different regions they come from. This is why you see the ranges scattered throughout the 64-bit address space.
The reason a large malloc might have a different kind of address than a small one is because of how malloc is allocating the memory. The small allocations usually come from the heap, which is at a lower address in typical x86_64 systems. But a large allocation doesn't come from the heap. If it did, then when it was freed there would be this huge hole where it was with other data still allocated before and after it. Inefficient. It's part of a problem known as fragmentation. So very large allocations use
mmap() to map a new region of memory just for the one allocation. This "anonymous mapping" as it's called will come from a different region than the heap and so you get an address that looks different.