Skip to content
Search

Dynamic memory allocation

lastmod 2018-08-17created 2015-06-172 edits

Dynamic memory allocation, or dynamic allocation of memory, refers to allocating memory space for use during run time in computer programming. When use is finished, the memory is returned so that the operating system can use it, and it can be reallocated when the next request comes. This contrasts with static memory allocation, in which memory is allocated at the moment the program runs, taking into account the amount of memory the program will use.

Dynamically allocated memory space stays as it is until the programmer explicitly frees it or garbage collection occurs. In languages without garbage collection, such as C/C++, dynamically allocated memory space stays in place until the user frees it. Because dynamic allocation is done from the process's heap area, the memory is freed when the process terminates, as the memory resources are returned to the operating system. However, while the process keeps running, the dynamically allocated areas remain, so if the program requests memory allocation beyond the size of the given heap area, the allocation fails. It is therefore advantageous to return areas that are no longer in use, and the programmer must free them using functions.

Dynamic allocation contrasts with automatic variables on the stack, whose space is freed automatically when a function ends or a variable goes out of scope. A process's static memory allocation is limited to an amount of memory already fixed when the process starts and is kept from the start of the process to its end, whereas dynamic allocation makes it possible to request needed memory from the operating system, receive it, and free it during the process's execution.

Dynamic allocation in the C language

Example memory map in the C language. Generalized and simplified.

See also

Favorite site