Cover Image for free vs delete in C++
98 views

free vs delete in C++

The free() and delete are used to deallocate memory in C and C++, respectively. They are similar in purpose, but they have key differences due to the programming languages they are associated with.

free() in C:

free() is a function provided by the C standard library (stdlib.h) to deallocate memory that was previously allocated using malloc(), calloc(), or realloc(). It is used in C as follows:

int* ptr = (int*)malloc(sizeof(int)); // Allocate memory using malloc
// ...
free(ptr); // Deallocate memory using free

Important points to note about free() in C:

  1. It works with memory allocated by functions like malloc, calloc, and realloc.
  2. It does not call destructors for C++ objects (as C does not have destructors).
  3. It does not check for null pointers, so you should ensure that the pointer is not null before calling free() to avoid undefined behavior.
  4. Using free() with memory allocated by new or objects with C++ destructors will result in undefined behavior.

delete in C++:

delete is an operator in C++ used to deallocate memory that was previously allocated using new. It is used in C++ as follows:

int* ptr = new int; // Allocate memory using new
// ...
delete ptr; // Deallocate memory using delete

Important points to note about delete in C++:

  1. It works with memory allocated by the new operator in C++.
  2. It calls the destructor of C++ objects before deallocating memory, making it suitable for managing the memory of objects with constructors and destructors.
  3. It automatically checks for null pointers, so you do not need to explicitly check for nullness before calling delete.
  4. Using delete with memory allocated by malloc or objects without C++ destructors will result in undefined behavior.
  5. There is a corresponding delete[] operator used to deallocate memory allocated for arrays using new[]. Similarly, malloc should be paired with free, and new[] with delete[].

In summary, when working with C++, it’s generally recommended to use new and delete for dynamic memory management, especially when dealing with objects that have constructors and destructors. Using free() in C++ should be avoided unless you are interfacing with C libraries or have specific requirements that necessitate it.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS