delete() and free() in C++

C++ProgrammingServer Side Programming

delete()

The delete operator is used to deallocate the memory. User has privilege to deallocate the created pointer variable by this delete operator.

Here is the syntax of delete operator in C++ language,

delete pointer_variable;

Here is the syntax to delete the block of allocated memory,

delete[ ] pointer_variable;

Here is an example of delete operator in C++ language,

Example

 Live Demo

#include <iostream>
using namespace std;
int main () {
   int *ptr1 = NULL;
   ptr1 = new int;
   float *ptr2 = new float(299.121);
   int *ptr3 = new int[28];
   *ptr1 = 28;
   cout << "Value of pointer variable 1 : " << *ptr1 << endl;
   cout << "Value of pointer variable 2 : " << *ptr2 << endl;
   if (!ptr3)
   cout << "Allocation of memory failed\n";
   else {
      for (int i = 10; i < 15; i++)
      ptr3[i] = i+1;
      cout << "Value of store in block of memory: ";
      for (int i = 10; i < 15; i++)
      cout << ptr3[i] << " ";
   }
   delete ptr1;
   delete ptr2;
   delete[] ptr3;
   return 0;
}

Output

Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of store in block of memory: 11 12 13 14 15

In the above program, three pointer variables are declared as ptr1, ptr2 and ptr3. The pointer variables ptr1 and ptr2 are initialized with the value using new() and ptr3 is storing the allocated block of memory by new() function.

int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;

Elements of array are printed by user and sum of elements is printed. To delete the allocated memory; delete ptr1, delete pt2 and delete[] ptr3 are used.

delete ptr1;
delete ptr2;
delete[] ptr3;

free()

The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of pointer which means it still points the same memory location.

Here is the syntax of free() in C language,

void free(void *pointer_name);

Here,

pointer_name − Any name given to the pointer.

Here is an example of free() in C language,

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   free(p);
   return 0;
}

Output

Enter elements of array : 32 23 21 28
Sum : 104

In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated.

int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));

The elements of array are given by the user and sum of their values are printed. The code to free the pointer is as follows −

free(p);
raja
Published on 05-Nov-2018 11:53:37
Advertisements