Reputation: 123
why do structure's data members memory allocated from lower to higher address in stack growing higher to lower? What is the mechanism in this process?
Upvotes: 1
Views: 570
Reputation: 40665
The stack is usually the only thing that grows downwards, while everything else does grow upwards. A structure on the stack, however, is the same as the same structure in the heap: an area of memory identified by the address of its first byte in memory, and the filling mechanism is the same as well.
So, the interesting question is not "why is a structure on the stack filled upwards" but "why does the stack grow downwards?"
The answer is simple: Because the stack grows downwards and the objects on it are identified by the address of their first byte, the stack pointer always points to the first element on the stack.
This might seem trivial, but it simplifies things quite a bit on the machine level. On the PowerPC, for instance, there was an instruction that saves a value at an offset of a pointer and updates this same pointer to the calculated address. This instruction can atomically allocate an entire stack frame and link it to the previous stack frame, and it would not work the other way around. (I hope that wasn't too much technical detail...)
Upvotes: 1
Reputation: 2664
One advantage is that Operating System is able to easily check whether overflow occurs in a process(program). Heap segment is usually growing from lower to higher when stack is growing from higher to lower. if two segment is gradually grow to be overlapped, OS can detect overflow in the process.
Here is a diagram for memory layout of C programs. Hope this help.
Also, such choice depends on OS designer. If you are a beginner, just don't care about it. Think easy.
Upvotes: 3