Stack and heap memory of a C program

I'm trying to understand the CPU's role in tracking a programs stack/heap allocation.

Reading some material, I've come across this:

The stack area traditionally adjoined the heap area and grew the opposite direction; when the stack pointer met the heap pointer, free memory was exhausted.

Are the stack and heap pointers stored in program specific registers?

If the stack pointer is pointing to the top of the stack, and (I'm assuming) the heap pointer is pointing to the end of the heap, how would these pointers ever meet without overwriting memory (overflow)?

How does this work in modern systems?


Are the stack and heap pointers stored in program specific registers?

CPUs of stack-based architectures (which represent the overwhelming majority of the CPUs in use today) have a special register for the stack pointer. This is possible because stack, by its very nature, does not get fragmented. Hence, a single pointer is sufficient.

There is no such thing as "heap pointer" because heap is potentially a fragmented data structure. Heap allocators keep a special table of memory fragments available for allocation, and adjust it when the program allocates and releases memory. Memory manager also keeps a pointer to the highest address that has been allocated from the heap.

If the stack pointer is pointing to the top of the stack, and (I'm assuming) the heap pointer is pointing to the end of the heap, how would these pointers ever meet without overwriting memory (overflow)?

Since stack pointer cannot cross without causing an error, many systems limit the size of the stack to a certain number, and make sure that the memory allocator would not let the high point of the heap to cross the upper limit of the stack.

Note: On systems that support concurrency there may be more than one stack active at a time. In this case the stacks are set up next to each other, with the upper limit monitored to detect stack overflows. Here is an article that describes techniques for detecting stack overflows.

链接地址: http://www.djcxy.com/p/79848.html

上一篇: 重新区别

下一篇: C程序的堆栈和堆内存