Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Stack Pointer and Program Counter?

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?

like image 472
Naasif Avatar asked Aug 20 '18 09:08

Naasif


People also ask

What is stack pointer and program counter in microprocessor?

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.

What is the difference between instruction pointer and program counter?

The Program Counter, also known as the Instruction pointer, is a processor register that indicates the current address of the program being executed.

What is the difference between the stack and stack pointer?

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.

What is the difference between stack pointer and frame pointer?

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.


1 Answers

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).

like image 133
cooperised Avatar answered Sep 19 '22 20:09

cooperised