Typical implementation of Memory Allocation for Variables
A typical implementation uses a runtime system stack.
Thus, the int
object n
on a system with 4-byte integers get this allocated off the stack and initialized to the value 5
. The gizmo
object w
requires 8 bytes to represent its two integer members.
The array of double
object z
requires ten times sizeof(double)
to store its elements. In each case, the system provides for the construction and initialization of these variables.
malloc will have to make a system call, to request memory from the OS.
Since OS allocators usually work with larger fixed sized blocks of memory, malloc will not have make this call every time, only when it has exhausted the memory it currently has. For local variables, it really is up to the compiler. The standard makes no mention of a stack. However, most likely you are on a common architecture running a common OS and common compiler.
Dynamic Memory Allocation
All of the code you have written up to now allocates space for data at compile time. You specify the variables and the arrays that you need in the code, and that is what will be allocated when the program starts, whether you need it or not.
Working with a fixed set of variables in a program can be very restrictive, and it's often wasteful. Dynamic memory allocation is allocating the memory you need to store the data you are working with at runtime, rather than having the amount of memory predefined when the program is compiled.
You can change the amount of memory your program has dedicated to it as execution progresses. By definition, dynamically allocated variables cannot be defined at compile time so they cannot be named in your source program. When you allocate memory dynamically, the space that is made available is identified by its address. The obvious and only place to store this address is in a pointer.
With the power of pointers and the dynamic memory management tools in C++, writing this kind of flexibility into your programs is quick and easy. You can add memory to your application when it is needed, then release the memory you have acquired when you are done with it. Thus the amount of memory dedicated to an application can increase and decrease as execution progresses.
Previously, I introduced the three kinds of storage duration that variables can have: 1) automatic, 2) static, and 3) dynamic and I discussed how variables of the first two varieties are created. Variables for which memory is allocated at runtime always have dynamic storage duration.