In Section 10.4.1 on page 393, we have discussed two ways of exchanging value1 and value2. Both methods require eight memory accesses. Can you write a code fragment that does this exchange using only six memory accesses? Make sure that your code does not alter the contents of any registers. Hint: Use the xchg instruction.
Temporary Storage of Data
The stack can be used as a scratchpad to store data on a temporary basis. For example, consider exchanging the contents of two 32-bit variables that are in the memory: value1 and value2. We cannot use
because both operands of xchg are in the memory. The code
works, but it uses two 32-bit registers. This code requires four memory operations. However, due to the limited number of general-purpose registers, finding spare registers that can be used for temporary storage is nearly impossible in almost all programs.
Â Â Â Â What if we need to preserve the contents of the EAX and EBX registers? In this case, we need to save these registers before using them and restore them as shown below:
This code requires eight memory accesses. Because the stack is a LIFO data structure, the sequence of pop instructions is a mirror image of the push instruction sequence.
Â Â Â Â Â An elegant way of exchanging the two values is
Notice that the above code does not use any general-purpose registers and requires eight memory operations as in the other example. Another point to note is that push and pop instructions allow movement of data from memory to memory (i.e., between data and stack segments). This is a special case because mov instructions do not allow memory-to-memory data transfer. Stack operations are an exception. String instructions, discussed in Chapter 12, also allow memory-to-memory data transfer.
Â Â Â Stack is frequently used as a scratchpad to save and restore registers. The necessity often arises when we need to free up a set of registers so they can be used by the current code. This is often the case with procedures as we show in Section 10.8.
Â Â Â It should be clear from these examples that the stack grows and shrinks during the course of a program execution. It is important to allocate enough storage space for the stack, as stack overflow and underflow could cause unpredictable results, often causing system errors.