
Chapter 05 Stack and Heap
In the previous chapter, we ran an investigation of the memory layout of a running process. System programming without knowing enough about the memory structure and its various segments is like doing surgery without knowing the anatomy of the human body. The previous chapter just gave us the basic information regarding the different segments in the process memory layout, but this chapter wants us to just focus on the most frequently used segments: Stack and Heap.
As a programmer, you are mostly busy working with Stack and Heap segments. Other segments such as Data or BSS are less in use, or you have less control over them. That's basically because of the fact that the Data and BSS segments are generated by the compiler, and usually, they take up a small percentage of the whole memory of a process during its lifetime. This doesn't mean that they are not important, and, in fact, there are issues that directly relate to these segments. But as you are spending most of your time with Stack and Heap, most memory issues have roots in these segments.
As part of this chapter, you will learn:
- How to probe the Stack segment and the tools you need for this purpose
- How memory management is done automatically for the Stack segment
- The various characteristics of the stack segment
- The guidelines and best practices on how to use the Stack segment
- How to probe the Heap segment
- How to allocate and deallocate a Heap memory block
- The guidelines and best practices regarding the usage of the Heap segment
- Memory-constrained environments and tuning memory in performant environments
Let's begin our quest by discussing the Stack segment in more detail.