I read somewhere that Stack Pointer is decremented to allocate space for local variables when a function is called.
I don't understand how it is true because according to me it should be incremented. Can somebody please explain?
I read somewhere that Stack Pointer is decremented to allocate space for local variables when a function is called.
I don't understand how it is true because according to me it should be incremented. Can somebody please explain?
First, it does not really matter if it is increased or decreased - the difference is only that the CPU increases or decreases SP on push/pop operations. This does not effect et al what is the essence of a stack: we get the data read from it exactly in the opposite order as we put it into.
The reason for it is historical: on machines without a paging-based virtual memory support, we have a fixed address space. There should be the code, the heap and the stack somehow placed - without overwriting each other.
The code part of the program typically does not change (except self-overwriting code on the ASM level - it is nearly surreal today, but it was rare even long ago). The size of the heap (data) segment sometimes grows, sometimes shrink, and also fragments. The stack only grows or shrinks, but it does not fragment.
This resulted that the typical memory layout of a process address space was this:
This results that the stack has to be at the end of the address space, but to make its growth possible, it has to be decreased on data insertion.
Another memory layouts were also possible, there were CPUs where the stack has grown on data insertion.
Later, with the appearance of the paging-based memory virtualization, this problem could have been roughly solved (although a decreasing stack were still better if the size of the virtual address space was not big enough). But there was no need to break compatibility for a zero-to-little improvement.