Cover Image for malloc() vs new in C++

malloc() vs new in C++

The malloc() and new are both used in C++ to allocate memory dynamically, but they are different in several important ways:

  1. Origin:
  • malloc(): It is a standard C library function. It’s also available in C++, but it’s not specific to C++.
  • new: It is a C++ operator designed for dynamic memory allocation. It’s part of the C++ language itself.
  1. Return Type:
  • malloc(): It returns a void* pointer, which must be cast to the appropriate type when used.
  • new: It returns a pointer to the allocated type, and you don’t need to cast it.
  1. Initialization:
  • malloc(): It does not call constructors for classes. The allocated memory contains raw, uninitialized data.
  • new: It calls the constructor for classes, ensuring proper initialization.
  1. Memory Size Calculation:
  • malloc(): You must manually specify the number of bytes to allocate.
  • new: You specify the type you want to allocate, and the compiler calculates the size based on the type.
  1. Failure Handling:
  • malloc(): It returns a null pointer (nullptr in C++) when it fails to allocate memory.
  • new: It throws an exception of type std::bad_alloc when it fails to allocate memory. You can also use the nothrow version of new to make it return nullptr on failure.

Here’s a comparison of how you would use malloc() and new to allocate memory for an integer:

Using malloc():

int* ptr = (int*)malloc(sizeof(int));
if (ptr == nullptr) {
    // Handle memory allocation failure
} else {
    *ptr = 42;
    // ...
    free(ptr); // Don't forget to free the memory when done

Using new:

int* ptr = new int;
if (ptr == nullptr) {
    // Handle memory allocation failure (unlikely due to exception)
} else {
    *ptr = 42;
    // No need to explicitly free memory; it's automatically done when the variable goes out of scope or you use delete

It’s generally recommended to use new (or better yet, smart pointers like std::shared_ptr or std::unique_ptr) when working with classes and objects, as it ensures proper initialization and automatic memory management. However, for low-level memory manipulation or compatibility with C code, you might still encounter malloc() and free(). Just be cautious when mixing them, as they have different behaviors.


The Tech Thunder

The Tech Thunder

The Tech Thunder