C++ Memory Management



C++ Memory management

The computer system has a finite memory available to allocate to multiple processes. When memory is inefficiently distributed then the number of processes that can be run simultaneous decreases, also programs are cleared from or loaded to memory more often depending on their priority leading to the system feeling sluggish to the user. To tackle this problem, we follow memory management principles and practices. Memory management controls and coordinated the allocation of memory blocks to the various running programs in order to optimize the system.
  1. Memory management can be implemented in the hardware, OS and application levels.At hardware level, it involves the primary and secondary memory modules such as RAM, SSD, HDD, etc. 
  2. At OS level, it involves distribution of memory for various processes while reserving some memory for OS processes. 
  3. At Application level, it involves the request and management of memory blocks required by the program itself.
In C/C++, the most basic form of data structure we learn about is Arrays. Arrays are used to homogeneous data, stored sequentially and generally declared at the compilation time. In this case, the programmers must allocate extra space to the array as the required size is not known until run-time. This can lead to unused memory during execution of the program.

To solve this issue, memory management operators are used. 

  1. In C, malloc() and calloc() functions are used to allocate memory dynamically at run-time. And free() function is used to de-allocate the dynamically allocated memory.
    1. malloc() – only allocated memory. 
    2. calloc() – allocated memory and initializes it to zero.
  2. In C++, new and delete operators are used to allocate and de-allocate memory respectively. By using the cstdlib.h library, malloc() and calloc() can also be used in C++.

new operator denotes a request for memory allocation on the Heap. If the request is granted depending on the availability of memory, then it returns the address of allocated memory.
  1. Syntax – pointer-variable = new data-type;
  2. Initialize memory while allocation – pointer-variable = new data-type(value);
  3. Allocation of block of memory – pointer-variable = new data-type[size];

Delete operator is used to de-allocate dynamically allocated memory.
  1. Syntax – delete pointer-variable;
  2. De-allocate dynamically allocated memory block – delete[] pointer-variable;
An example is given below -


The output for example was -



Comments

Post a Comment

Popular posts from this blog

Operator Overloading in C++

C++ File Handling

Application Linked list