I know basic stuffs like when you run a process, it will load environment variables and the parameters to the stack; or how rsp, rbp registers be doing when we run a function. But, what thing and when does the stack/heap actually created when we run a process?
-
https://stackoverflow.com/questions/17671423/where-is-the-stack-memory-allocated-from-for-a-linux-process – user123 Jul 15 '21 at 09:11
3 Answers
The stack is allocated at launch time of the process with a default size. It also has a maximum size. If the stack grows past its default size, the kernel checks whether the stack is bigger than its maximum size. It allocates more pages to the stack if it is smaller or kills the process if it is bigger.
The heap is allocated a region of virtual memory but not of physical memory. The heap will have a reserved region of virtual memory so that it can freely grow within it. When you ask for dynamic memory using the new operator in C++, you make a system call in the kernel to ask that it allocates a part of that virtual address space reserved for the heap in the physical address space. Once a portion of the physical address space has been allocated to your process, you can use it in your application freely.
Most C++ standard library implementations will have code that will follow how the heap grows and attempt to avoid internal fragmentation. The smallest unit of allocation in most OSes is 4KB. If you ask for, let's say, 1024 bytes of data, one page is allocated to your process. The process thus have one full page allocated. There is some memory lost here to internal fragmentation. The C++ standard library implementation thus keeps track of the allocated pages for you so that when you ask for more memory it will use the same page for your memory needs instead of requesting several pages for nothing.

- 2,510
- 2
- 6
- 20
There are four components on the ram: the code itself, global variables, stack, and heap.
In c++, the first three gets created during compilation, heap gets created when you create it(eg. int *ptr = new int[10];
)
In python, everything is pointers (stack memory only contains the pointers, actual values in heap), meaning all four are created during compilation(interpreting)

- 105
- 1
- 1
- 6
-
Not sure that the stack and heap are *created* when you say ... rather, that's when memory from them is allocated. On most OSes, they are (both) created - or made available to the running program - at startup. – Adrian Mole Jul 16 '21 at 14:49