c-plus-plus
  1. c-plus-plus-free-vs-delete

C++ Pointers: Free vs Delete

Syntax

The syntax for free() and delete in C++ are as follows:

free(pointer);
delete pointer;

Example

Consider the following code snippet:

int *ptr = new int;
*ptr = 42;

// using free()
free(ptr);

// using delete
int *ptr2 = new int;
*ptr2 = 69;
delete ptr2;

Output

Both free() and delete free the memory allocated to the pointer. There is no output for these functions.

Explanation

free() and delete are used to deallocate memory that is dynamically allocated using malloc() or new. free() is a C language function whereas delete is a C++ language operator.

free() simply deallocates the memory pointed to by the pointer, whereas delete also calls the destructor of the object if it is a class type.

It is important to note that free() cannot be used to deallocate memory allocated by new and delete cannot be used to deallocate memory allocated by malloc().

Use

free() and delete are commonly used to prevent memory leaks in C++ programs. Memory leaks occur when memory is allocated but not deallocated, leading to a buildup of memory usage over time. It is important to use one of these functions whenever dynamic memory allocation is used in a program.

Important Points

  • free() is a C function whereas delete is a C++ operator
  • free() only deallocates memory whereas delete also calls the destructor of objects
  • free() cannot be used to deallocate memory allocated by new and delete cannot be used to deallocate memory allocated by malloc()

Summary

In C++, free() and delete are used to deallocate memory that is dynamically allocated using malloc() and new, respectively. They prevent memory leaks and should be used whenever dynamic memory allocation is used in a program. free() is a C function whereas delete is a C++ operator. delete also calls the destructor of objects whereas free() only deallocates memory.

Published on: