English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C ++delete() and free() in

delete()

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

This is C ++The syntax of delete operator in language,

delete pointer_variable;

This is the syntax for deleting allocated memory block,

delete[ ] pointer_variable;

This is C ++Example of delete operator in language,

Example

#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 result

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

Three pointer variables are declared as ptr in the above program1, ptr2and ptr3. Pointer variable ptr1and ptr2are initialized with value,new()and ptr3bynew()method to store the allocated memory block.

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

The elements of the array are printed by the user, the sum of the elements is printed. Delete the allocated memory; use delete ptr1, delete pt2and delete[] ptr3.

delete ptr1;
delete ptr2;
delete[] ptr3;

free()

The functionfree()is used to free allocated memorymalloc(). It does not change the value of the pointer, which means it still points to the same memory location.

This isfree()C language syntax,

void free(void *pointer_name);

Here,

pointer_name-any name given to a pointer.

This isfree()C language example,

Example

#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 result

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

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

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

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

free(p);