Process Memory Structure
In this chapter, we are going to talk about memory and its structure within a process. For a C programmer, memory management is always a crucial topic, and applying its best practices requires a basic knowledge about memory structure. In fact, this is not limited to C. In many programming languages such as C++ or Java, you need to have a fundamental understanding of memory and the way it works; otherwise, you face some serious issues that cannot be easily traced and fixed.
You might know that memory management is fully manual in C, and more than that, the programmer is the sole responsible person who allocates memory regions and deallocates them once they're no longer needed.
Memory management is different in high-level programming languages such as Java or C#, and it is done partly by the programmer and partly by the underlying language platform, such as Java Virtual Machine (JVM) in the case of using Java. In these languages, the programmer only issues memory allocations, but they are not responsible for the deallocations. A component called the garbage collector does the deallocation and frees up the allocated memory automatically.
Since there is no such garbage collector in C and C++, having some dedicated chapters for covering the concepts and issues regarding memory management is essential. That's why we have dedicated this chapter and the next to memory-related concepts, and these chapters together should give you a basic understanding of how memory works in C/C++.
Throughout this chapter:
- We start by looking at the typical memory structure of a process. This will help us to discover the anatomy of a process and the way it interacts with the memory.
- We discuss static and dynamic memory layouts.
- We introduce the segments found in the aforementioned memory layouts. We see that some of them reside in the executable object file and the rest are created while the process is loading.
- We introduce the probing tools and commands which can help us to detect the segments and see their content, both inside an object file and deep within a running process.
As part of this chapter, we get to know two segments called Stack and Heap. They are part of the dynamic memory layout of a process and all the allocations and deallocations happen in these segments. In the following chapter, we will discuss Stack and Heap segments in a greater detail because in fact, they are the segments that a programmer interacts with the most.
Let's start this chapter by talking about the process memory layout. This will give you an overall idea about how the memory of a running process is segmented, and what each segment is used for.