When a C++ program is started there are a few memory segments/areas allocated:
For the program itself and the used libraries. The size of the program and its libraries is known in advance.
For global variables and for constants. Similarly, the sizes of these memory segments are known at compile-time.
However with the stack and heap are in a different situation. The sizes of these seem to not be fixed.
I am by no means a specialist in the inner workings of C++ so please consider correcting any wrong assumptions I make as part of the question.
For the sake of this question let's assume we are running on Windows10 and using Visual C++ (please tell me if the answer can differ on any other major platforms).
My questions are:
Is the heap dynamic in size? (i.e. can the size of the heap change during run-time?) I would assume it is since you can always
malloc
more space if you need to.Is the stack dynamic in size? This is trickier since we know what functions will be called and what/how many local variables they will have but what makes me think it might be dynamic in size is that things like recursion, lambdas function pointers, reading values from other files can make it impossible to tell how many times a function will be called.
If the answer to the 2 above questions is "yes" then how are these memory zones places in the physical memory? Are they contiguous with one another and with the program memory? (i.e. is the actual program from address
0
to addressx
, the stack from addressx
tox+k
and the heap from(x+k)
to(x+k)+p
?)If the answer to 3. is "yes" then what happens when a memory area "in the middle" like the stack needs to be resized?
This is purely an educational question. In the answer please correct any wrong assumptions I have made.