delete and free

delete operator and free() function in C++

difference_between_delete_and_free()_in_c++

In C++, delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

free() function

Basically, it was used in C programming language, to free the run time allocated memory, it is a library function and it can also be used in C++ for the same purpose. free() is declared in stdlib.h header file.

free(pointer_name);

delete operator

delete is an operator in C++ programming language, it is used to free the run time allocated memory.

delete pointer_name;

Differences between delete operator and free() function

Both are used for same purpose, but still they have some differences, the differences are:

  1. delete is an operator whereas free() is a library function.
  2. delete free the allocated memory and calls destructor. But free() de-allocate memory but does not call destructor.
  3. delete is faster than free() because an operator is always faster than a function.

Example :

#include<stdio.h> 
#include<stdlib.h> 
int main() 
{ 
    int x; 
    int *ptr1 = &x; 
    int *ptr2 = (int *)malloc(sizeof(int)); 
    int *ptr3 = new int; 
    int *ptr4 = NULL; 
  
    /* delete Should NOT be used like below because x is allocated  
        on stack frame */
    delete ptr1;   
  
    /* delete Should NOT be used like below because x is allocated  
        using malloc() */
    delete ptr2;   
  
    /* Correct uses of delete */
    delete ptr3; 
    delete ptr4; 
  
    getchar(); 
    return 0; 
} 


If you like dEexams.com and would like to contribute, you can also write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Python if , elif and else

Python Conditions and If statements

  • 0
Python for beginners

Learning Python Part 1

  • 3
Struct Alignment and Padding

Struct Alignment and Padding in C++ And C

  • 0
Friend function

Friend function C++

  • 0
Pointers

C++ Pointers

  • 0
Structures

C++ Structures

  • 0
Types of Inheritance in C++

Inheritance and access specifiers C++

  • 0
Java date pattern

Java Date Pattern Syntax

  • 0
Java Date and Calendar

Java Date formats

  • 0
JAVA Data Type

Data types in Java

  • 0
Java unreachable code

Unreachable Code Error in Java

  • 0

Post Comment

Comments(0)

WEB TECHNOLOGY

Articles

×

Forgot Password

Please enter your email address below and we will send you information to change your password.