Size of Heap, Stack and Data Memory Units

There are several parts to this question.

According to most of the resources available on net and according to the text books as well, heap and stack memory grow in opposite directions.

  • Do Heap and Stack actually always grow in opposite directions towards each other, especially when extra memory is allocated by the OS for Heap memory?

  • Consider that initially in the program, only heap allocations take place and minimal Stack memory is used. Hence, Heap will cover almost entire combined memory allocated for Stack and heap. Afterwards, Stack starts to grow. Will an error be thrown or will new memory location be allotted for Stack to grow to its maximum limit(maximum limit = limit shown by "ulimit -s" command) ? If new location can be allotted, then doesn't it violate the condition that in Stack addresses are always assigned in order?

  • Is there any pre-defined limit on the memory usage by initialized and uninitialized variables stored in Data section?


  • Answers:

    Do Heap and Stack actually always grow in opposite directions towards each other,
    especially when extra memory is allocated by the OS for Heap memory?  
    

    Heaps and stacks are an implementation detail and not required by the language specification. The directions they grow are not necessarily toward each other; they can grow anyway they want.

    Consider that initially in the program,  
    only heap allocations take place and minimal Stack memory is used.  
    Hence, Heap will cover almost entire combined memory allocated  
    for Stack and heap. Afterwards, Stack starts to grow.  
    Will an error be thrown or will new memory location be allotted  
    for Stack to grow to its maximum limit
    (maximum limit = limit shown by "ulimit -s" command)?  
    If new location can be allotted, then doesn't it violate the condition  
    that in Stack addresses are always assigned in order?  
    

    If your heap and stack grow towards each other, overwriting may take place. You will only receive notification of overrunning if your memory allocator checks for out of space or you have a utility that checks the run-time stack allocation. Remember, not all platforms are Linux or Windows PCs; many are constrained embedded systems.

    Is there any pre-defined limit on the memory usage  
    by initialized and uninitialized variables  
    stored in Data section?  
    

    Yes, there must be memory somewhere for the variables. Variables may be paged out to an external device by the OS. There is a possibility that the variables are not variables but hardware registers. Again, this is all platform specific. The rule imposed by the language standard is that the variables must be addressable and static or auto variables must have a unique address (the One Definition Rule, ODR).

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

    上一篇: 物理内存堆和堆栈在哪里?

    下一篇: 堆,堆栈和数据存储单元的大小