Memory Allocation/Memory Management?
Memory management is a process of managing computer memory, assigning the memory space to the programs to improve the overall system performance.
Why is memory management required?
The golden rule of computers states that anything and everything (data or instruction) that needs to be processed must be loaded into internal memory before its processing takes place. Therefore, every data and instruction that is being executed must be allocated some area in the main (internal) memory. The main (internal) memory is allocated in two ways: statically and dynamically.
As we know that arrays store homogeneous data, so most of the time, memory is allocated to the array at the declaration time. Sometimes the situation arises when the exact memory is not determined until runtime. To avoid such a situation, we declare an array with a maximum size, but some memory will be unused. To avoid the wastage of memory, we use the new operator to allocate the memory dynamically at the run time.
Static Memory Allocation
When the amount of memory to be allocated is known beforehand and the memory is allocated during compilation itself, it is referred to as static memory allocation. For instance, when you declare a variable as follows:
int a; (Memory required: 4 bytes)
int a[10]; (Memory required: 4*10=40 bytes)
Then, in such a case the computer knows that what the length of int variable is. Generally, it is 4 bytes. So, a chunk of 4 bytes of internal memory will be allocated for variable “a” during compilation itself. Thus, it is an example of static memory allocation.
Dynamic Memory Allocation
When the amount of memory to be allocated is not known beforehand rather it is required to allocate (main) memory as and when required during runtime (when the program is actually executing) itself, then, the allocation of memory at run time is referred to as dynamic memory allocation.
C++ offers two operators for dynamic memory allocation namely new and delete. The operator “new” allocates the memory dynamically and returns a pointer storing the memory (base) address of the allocated memory. The operator “delete” deallocates the memory (the reverse of new) pointed by the given pointer.
Memory Management Operators
In C language, we use the malloc() or calloc() functions to allocate the memory dynamically at run time, and free() function is used to deallocate the dynamically allocated memory.
C++ also supports these functions, but C++ also defines unary operators such as new and delete to perform the same tasks, i.e., allocating and freeing the memory.