As we always know the procedure of executing task by a microprocessor is just executing binary instructions from memory one by one and there is a program counter which holds the address of the next instruction. So this is how processor executes it's tasks if I am not wrong. But there is also another pointer named Stack Pointer which does almost same thing like the program counter. My question is why we need a Stack Pointer to point address of memory(Stack)? Can somebody tell me about the main difference between Stack Pointer and program counter?
The Stack Pointer register will hold the address of the top location of the stack. And the program counter is a register always it will hold the address of the memory location from where the next instruction for execution will have to be fetched.
The Program Counter, also known as the Instruction pointer, is a processor register that indicates the current address of the program being executed.
A stack is a specialized buffer that is used by a program's functions to store data such as parameters, local variables and other function-related information. The stack pointer -- also referred to as the extended stack pointer (ESP) -- ensures that the program always adds data to the right location in the stack.
The compiler passes parameters and return variables in a block of memory known as a frame. The frame is also used to allocate local variables. The stack elements are frames. A stack pointer (sp) defines the end of the current frame, while a frame pointer (fp) defines the end of the last frame.
Well, they're fundamentally different concepts. They both contain memory addresses, but remember that both instructions and data are held in (effectively) the same memory space.
The program counter contains the address of the instruction that's currently executing. In fact the CPU uses the value in the program counter to fetch the instructions before it executes them. As instructions are executed, its value is incremented, and if the code branches it will have its value forcibly overwritten.
The stack pointer contains the address of the top of the hardware stack, which is a region of memory that the running code uses as a scratchpad. Values are stored there temporarily, arguments to functions are sometimes put there, and code addresses can be stored there too (for example when one function calls another).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With