What About The Stack?
This lesson addresses how segmentation works in the stack with the help of an example.
We'll cover the following
Thus far, we’ve left out one important component of the address space: the stack. The stack has been relocated to the physical address 28KB in the diagram above, but with one critical difference: it grows backwards (i.e., towards lower addresses). In physical memory, it “starts” at
The first thing we need is a little extra hardware support. Instead of just base and bounds values, the hardware also needs to know which way the segment grows (a bit, for example, that is set to when the segment grows in the positive direction, and for negative). Our updated view of what the hardware tracks is seen in the figure below:
With the hardware understanding that segments can grow in the negative direction, the hardware must now translate such virtual addresses slightly differently.
Example
Let’s take an example stack virtual address and translate it to understand the process.
In this example, assume we wish to access virtual address 15KB, which should map to physical address 27KB. Our virtual address, in binary form, thus looks like this: (hex 0x3C00). The hardware uses the top two bits () to designate the segment, but then we are left with an offset of 3KB. To obtain the correct negative offset, we must subtract the maximum segment size from 3KB: in this example, a segment can be 4KB, and thus the correct negative offset is 3KB minus 4KB which equals -1KB. We simply add the negative offset (-1KB) to the base (28KB) to arrive at the correct physical address: 27KB. The bounds check can be calculated by ensuring the absolute value of the negative offset is less than or equal to the segment’s current size (in this case, 2KB).
Get hands-on with 1400+ tech skills courses.