Skip to main content

Linux Virtual Memory - Dynamic Memory

In the last lesson we reviewed the memory attribute of Static vs Dynamic, and how dynamic memory is mapped into variable locations in the virtual memory map, and whose size is not determined before runtime. I need to briefly go over the different types of dynamic memory so that the examples in the next part will not be confusing.

The odd ball here is file-backed dynamic memory. This is done via a system call, mmap (for memory map,) that is made at run-time to map a file onto the virtual address space. The basic mechanics is that any read or write oprations on the memory locations mapped to the file will be made to/from the file. I will do a deep dive on mmap and memory mapped files in the future.

There are then 3 types of anonymous dynamic memory. The Stack, the heap, and anonymous mmap.

Anonymous mmap is just like the file-backed example from above, except that it exists only in memory and not on the filesystem.

The Stack and heap are special in that each process will only have 1 heap, and each thread in a process will only have 1 stack. In both cases, they're each contiguous within the virtual memory space. This is not a programming tutorial, so I'm not going to go into deep theory, but as a high level summary, the stack is a data structure used to manage local variables used in C, and the heap is used for global variables that are dynamically allocated. Each time a function is called, a frame is set up on the stack to hold the variables local to that function's scope. If data needs to persist between function calls, the data is put on the heap and a pointer to that data is passed between functions.

If you're not a C programmer, I'll be posting a primer later that will run through everything you need to know for this series, just know that with few exceptions everything that runs on Linux is either programmed in C, interpreted by a program that was written in C, or makes use of wrappers that call the system's C libraries.

In the next lesson we will be looking at example memory mappings, reading executable file metadata, and how learning how the mappings can be manipulated with system calls.

Previous in series : Memory Types