|"Also, what are times when they would be used?"|
Dynamic Memory Allocation (normally abbreviated to DMA) is used to store large blocks of data that cannot fit on the stack and/or has not business being on the stack. The general rule of thumb is use the stack for simple automatic storage such as "int
" and "double
" and low-cost structures like this:
In other cases, DMA is useful for when you want to reserve some memory prior to its use because that memory may not be available later on. For example, let's say you had 128MB of system memory available and your application needs 100MB of that memory. In addition, let's also say that another application wants 50MB of memory. If your application reserved that memory before the other application, your application would have the memory it needs for when it does actually need it.
DMA is also used to pass information around so that the information is not subject to the scoping rules. For instance, in the following code, "A_
" will remain existent until the end of the function.
void Function( )
However, because "A_
" is restricted to the scope in which it was defined, we can only work with it while the function is being called -- we could declare it static (but that won't solve anything) or we could declare it global (not recommended as this would create a dependency). This is where DMA comes in. We could allocate space on the heap for "A_
", work with "A_
" and then return a pointer to "A_
" which the calling function can use to refer to "A_
's" memory. For example:
int *CreateAndUseA( int InitialValue_ = 0 )
int *A_( ::new int( InitialValue_ ) );
// Work with A_...
return( A_ );
void DoSomethingWithA( )
int *A_( CreateAndUseA( ) );
*A_ ... ;
Sure, you could declare "A_
" static and return a pointer to it, but as I said, for large structures or large arrays, "A_
" would be better off on the heap than the stack anyway.
DMA is also used in:
● Linked-lists, stacks, de/queues, sequence containers, etcetera.
● Polymorphism normally uses the heap.
● Graphics: you need to allocate memory from the GPU.
● Garbage collection.