This may seem like a very basic question, but its been in my head so:
When we allocate a local variable, it goes into stack. Similarly dynamic allocation cause the v
Mr. Eberle's answer is 100% correct, but since Google shows this as the first answer when searching for malloc heap or stack
, I have to add that malloc()
allocates data on the heap 'most' of the time. If the allocated data was larger than MMAP_THRESHOLD which is usually 128kb on 32-bit systems, malloc()
will not use the heap and instead allocates the data in an Anonymous Memory Segment located usually below the stack, growing in the direction of low memory.
This is the same region that dynamically loaded libraries are located (libc.so
, etc.). Here's the relevant passage from man malloc:
Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2). When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2). MMAP_THRESHOLD is 128 kB by default, but is adjustable using mallopt(3). Prior to Linux 4.7 allocations performed using mmap(2) were unaffected by the RLIMIT_DATA resource limit; since Linux 4.7, this limit is also enforced for allocations performed using mmap(2).
As a practical example, feel free to check the following post. It basically allocates 300kb with malloc()
and then runs pmap
to show the relevant memory segment.