C++ memory_resource::deallocate() Function



The C++ memory_resource::deallocate() function is used for deallocating the memory. which means it is used for freeing the memory that was previously allocated using the allocate() function.

Deallocating memory is important to avoid memory leaks in the program. If you allocate memory using the allocate() function, you must deallocate it using the deallocate() function to avoid memory leaks. You can use the freed memory for other purposes.

Exception: We should only call deallocate() function for the memory that was allocated using the allocate() function. If you try to deallocate memory that was not allocated using the allocate() function, it will result in undefined behaviour.

Syntax

Following is the syntax for std::memory_resource::deallocate() function.

void deallocate(void *p, size_t n);

Parameters

The parameters for the deallocate() function are as follows:

  • p − It indicates the pointer to the memory block that you want to deallocate.

  • n − It indicates the number of bytes to deallocate.

Return Value

This function does not return any value it just free the memory.

Example 1

Now, we will understand how to deallocate memory for an array of integers using deallocate() function.

We have allocated memory for 5 integers using allocate() function, then we have assigned values to each element of the array, then we have printed the values of the array. After that, we have deallocated the memory using deallocate() function.

#include <iostream>
#include <memory>

using namespace std;

int main () {
   std::allocator<int> alloc;
   int *p = alloc.allocate(5);

   for(int i = 0; i < 5; i++) {
      alloc.construct(&p[i], i);
   }

   for(int i = 0; i < 5; i++) {
      cout << p[i] << endl;
   }

   for(int i = 0; i < 5; i++) {
      alloc.destroy(&p[i]);
   }

   alloc.deallocate(p, 5);
   return 0;
}

Output

If we run the above code it will generate the following output −

0
1
2
3
4

Example 2

Now, we will understand how to deallocate memory for an array of characters using deallocate() function.

Similar to last example we have allocated memory but this time for 5 characters using allocate() function, then we have assigned values to each element of the array, then printed the values of the array. After that, needed to deallocate() function.

#include <iostream>
#include <memory>
using namespace std;
int main(){
   std::allocator<char> alloc;
   char* p = alloc.allocate(5);

   for(int i = 0; i < 5; i++) {
      alloc.construct(&p[i], 'A' + i);
   }

   for(int i = 0; i < 5; i++) {
      cout << p[i] << endl;
   }

   for(int i = 0; i < 5; i++) {
      alloc.destroy(&p[i]);
   }

    return 0;
}

Output

Following is the output of the above code −

A
B
C
D
E
cpp_memory_resource.htm
Advertisements