Why can stack usage take place without prior allocating the memory?

The virtual address space of a process begins with the text , data and bss segments of the process. After this heap allocations are placed, thus heap grows towards larger memory addresses. However, before using a portion of the heap a memory block has to be allocated ( valloc and the like) otherwise a segfault occurs (or should occur).

The stack grows from an initial large address in virtual address space toward smaller values. As far as I know this works without virtual memory allocation. How is it possible to use the stack without prior memory allocation when in the case of the heap this is not possible? (Its the same linear virtual address space.)

As far ai know alloca is implemented just as sub esp, <size> . But the region of virtual address space the stack is using must have been allocated somehow prior to this, right?


It does segfault, in some way. This is kind of "lazy" optimization. Operating systems cheat as much as they can, as long as the difference is not externally observable.

However, the trap does not result in generating a signal (which by default kills the process) as with a normal segfault. Instead, the operating system verifies that the allowable thread size has not been exceeded, and then pulls a new page from the zero pool.

Under Windows, that mechanism is fancily named "guard page", I am not aware of a similar naming under Linux. Either way, a guard page is technically nothing but a write-protected page (or a non-existing page) which is remembered by the OS as being "special", so some particular action can occur when it's touched.

This is very similar to how dynamic allocation ( malloc , which calls sbrk ) works, too. When you allocate memory, not much really happens as long as you don't access the allocated memory. The only thing that happens is that the OS "remembers" that you grew the data segment.
If now a fault happens, the OS will create the page, or pull it from the zero pool respectively, and pretend it has been there all the time. You never know it wasn't there before.

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

上一篇: MapUserPhysicalPages(AWE重新映射)影响ASLR吗?

下一篇: 为什么不预先分配内存就可以使用堆栈?