Unless you are forced to use C, you should never use malloc. Always use new.

If you need a big chunk of data just do something like:

char *pBuffer = new char[1024];

Be careful though this is not correct:

//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;

Instead you should do this when deleting an array of data:

//This deletes all items in the array
delete[] pBuffer;

The new keyword is the C++ way of doing it, and it will ensure that your type will have its constructor called. The new keyword is also more type-safe whereas malloc is not type-safe at all.

The only way I could think that would be beneficial to use malloc would be if you needed to change the size of your buffer of data. The new keyword does not have an analogous way like realloc. The realloc function might be able to extend the size of a chunk of memory for you more efficiently.

It is worth mentioning that you cannot mix new/free and malloc/delete.

Note: Some answers in this question are invalid.

int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements
Answer from Brian R. Bondy on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ malloc-vs-new
malloc() vs new - GeeksforGeeks
July 8, 2021 - Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ new-vs-malloc-and-free-vs-delete-in-c
new vs malloc() and free() vs delete in C++ - GeeksforGeeks
July 15, 2025 - Both malloc() and new are used to allocate the memory dynamically in heap. But "new" does call the constructor of a class whereas "malloc()" does not.
Top answer
1 of 16
516

Unless you are forced to use C, you should never use malloc. Always use new.

If you need a big chunk of data just do something like:

char *pBuffer = new char[1024];

Be careful though this is not correct:

//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;

Instead you should do this when deleting an array of data:

//This deletes all items in the array
delete[] pBuffer;

The new keyword is the C++ way of doing it, and it will ensure that your type will have its constructor called. The new keyword is also more type-safe whereas malloc is not type-safe at all.

The only way I could think that would be beneficial to use malloc would be if you needed to change the size of your buffer of data. The new keyword does not have an analogous way like realloc. The realloc function might be able to extend the size of a chunk of memory for you more efficiently.

It is worth mentioning that you cannot mix new/free and malloc/delete.

Note: Some answers in this question are invalid.

int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements
2 of 16
172

The short answer is: don't use malloc for C++ without a really good reason for doing so. malloc has a number of deficiencies when used with C++, which new was defined to overcome.

Deficiencies fixed by new for C++ code

  1. malloc is not typesafe in any meaningful way. In C++ you are required to cast the return from void*. This potentially introduces a lot of problems:

    #include <stdlib.h>
    
    struct foo {
      double d[5];
    }; 
    
    int main() {
      foo *f1 = malloc(1); // error, no cast
      foo *f2 = static_cast<foo*>(malloc(sizeof(foo)));
      foo *f3 = static_cast<foo*>(malloc(1)); // No error, bad
    }
    
  2. It's worse than that though. If the type in question is POD (plain old data) then you can semi-sensibly use malloc to allocate memory for it, as f2 does in the first example.

    It's not so obvious though if a type is POD. The fact that it's possible for a given type to change from POD to non-POD with no resulting compiler error and potentially very hard to debug problems is a significant factor. For example if someone (possibly another programmer, during maintenance, much later on were to make a change that caused foo to no longer be POD then no obvious error would appear at compile time as you'd hope, e.g.:

    struct foo {
      double d[5];
      virtual ~foo() { }
    };
    

    would make the malloc of f2 also become bad, without any obvious diagnostics. The example here is trivial, but it's possible to accidentally introduce non-PODness much further away (e.g. in a base class, by adding a non-POD member). If you have C++11/boost you can use is_pod to check that this assumption is correct and produce an error if it's not:

    #include <type_traits>
    #include <stdlib.h>
    
    foo *safe_foo_malloc() {
      static_assert(std::is_pod<foo>::value, "foo must be POD");
      return static_cast<foo*>(malloc(sizeof(foo)));
    }
    

    Although boost is unable to determine if a type is POD without C++11 or some other compiler extensions.

  3. malloc returns NULL if allocation fails. new will throw std::bad_alloc. The behaviour of later using a NULL pointer is undefined. An exception has clean semantics when it is thrown and it is thrown from the source of the error. Wrapping malloc with an appropriate test at every call seems tedious and error prone. (You only have to forget once to undo all that good work). An exception can be allowed to propagate to a level where a caller is able to sensibly process it, where as NULL is much harder to pass back meaningfully. We could extend our safe_foo_malloc function to throw an exception or exit the program or call some handler:

    #include <type_traits>
    #include <stdlib.h>
    
    void my_malloc_failed_handler();
    
    foo *safe_foo_malloc() {
      static_assert(std::is_pod<foo>::value, "foo must be POD");
      foo *mem = static_cast<foo*>(malloc(sizeof(foo)));
      if (!mem) {
         my_malloc_failed_handler();
         // or throw ...
      }
      return mem;
    }
    
  4. Fundamentally malloc is a C feature and new is a C++ feature. As a result malloc does not play nicely with constructors, it only looks at allocating a chunk of bytes. We could extend our safe_foo_malloc further to use placement new:

    #include <stdlib.h>
    #include <new>
    
    void my_malloc_failed_handler();
    
    foo *safe_foo_malloc() {
      void *mem = malloc(sizeof(foo));
      if (!mem) {
         my_malloc_failed_handler();
         // or throw ...
      }
      return new (mem)foo();
    }
    
  5. Our safe_foo_malloc function isn't very generic - ideally we'd want something that can handle any type, not just foo. We can achieve this with templates and variadic templates for non-default constructors:

    #include <functional>
    #include <new>
    #include <stdlib.h>
    
    void my_malloc_failed_handler();
    
    template <typename T>
    struct alloc {
      template <typename ...Args>
      static T *safe_malloc(Args&&... args) {
        void *mem = malloc(sizeof(T));
        if (!mem) {
           my_malloc_failed_handler();
           // or throw ...
        }
        return new (mem)T(std::forward(args)...);
      }
    };
    

    Now though in fixing all the issues we identified so far we've practically reinvented the default new operator. If you're going to use malloc and placement new then you might as well just use new to begin with!

๐ŸŒ
Medium
medium.com โ€บ @sofiasondh โ€บ what-is-the-difference-between-new-and-malloc-160c0f38f45f
What is the Difference Between New and Malloc? | by Sofia Sondh | Medium
January 17, 2025 - Working in C: If you are programming in C, malloc is the standard way to allocate dynamic memory since new is not available.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 141700
new vs. malloc - C++ Forum
For an object of type int, the differences are minor: They call different functions (you can provide your own function to be called by new within the same program, but you have to resort to the OS help to replace malloc) They handle errors differently (new will call the user-provided handler if one was provided and throw an exception, while malloc would return a null pointer) The cleanup is different (delete and free, respectively)
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ use of ::operator new vs malloc
r/cpp_questions on Reddit: Use of ::operator new vs malloc
March 20, 2022 -

Hi there, I'm currently reimplementing the small block memory allocator used by Box2D to get a better understanding of what it's doing, and I was wondering why, despite being a C++ library and not C, it uses malloc and free as its default allocator when allocating larger blocks of memory.

Is there a good reason for this or just an example of using C in C++? I assume new and delete are not used because they don't want to initialise anything in the newly allocated area, but wouldn't ::operator new and ::operator delete do this however?

Have I understood correctly that ::operator new and ::operator delete do largely the same thing as malloc and free?

๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ C_dynamic_memory_allocation
C dynamic memory allocation - Wikipedia
3 weeks ago - The implementation of memory management depends greatly upon operating system and architecture. Some operating systems supply an allocator for malloc, while others supply functions to control certain regions of data. The same dynamic memory allocator is often used to implement both malloc and the operator new in C++.
๐ŸŒ
Quora
quora.com โ€บ Learning-programming-In-what-cases-do-I-use-malloc-vs-new
Learning programming: In what cases do I use malloc vs new? - Quora
The new and delete operators are not available in C. In C++, you should use the new and delete operators (single-object form and array form, as appropriate). While it is possible to use the ma...
Top answer
1 of 7
77

new and delete are C++ specific features. They didn't exist in C. malloc is the old school C way to do things. Most of the time, you won't need to use it in C++.

  • malloc allocates uninitialized memory. The allocated memory has to be released with free.
  • calloc is like malloc but initializes the allocated memory with a constant (0). It needs to be freed with free.
  • new initializes the allocated memory by calling the constructor (if it's an object). Memory allocated with new should be released with delete (which in turn calls the destructor). It does not need you to manually specify the size you need and cast it to the appropriate type. Thus, it's more modern and less prone to errors.
2 of 7
24

new/delete + new[]/delete[]:

  • new/delete is the C++ way to allocate memory and deallocate memory from the heap.
  • new[] and delete[] is the C++ way to allocate arrays of contiguous memory.
  • Should be used because it is more type safe than malloc
  • Should be used because it calls the constructor/destructor
  • Cannot be used in a realloc way, but can use placement new to re-use the same buffer of data
  • Data cannot be allocated with new and freed with free, nor delete[]

malloc/free + family:

  • malloc/free/family is the C way to allocate and free memory from the heap.
  • calloc is the same as malloc but also initializes the memory
  • Should be used if you may need to reallocate the memory
  • Data cannot be allocated with malloc and freed with delete nor delete[]

Also see my related answer here

Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ malloc-vs-new-in-c-cplusplus
malloc() vs new() in C/C++
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); The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the memory to the pointer variable and returns its address. Here is the syntax of new operator in C++ language,
๐ŸŒ
PREP INSTA
prepinsta.com โ€บ home โ€บ c++ online tutorials โ€บ c++ malloc() vs new
C++ malloc() vs new | PrepInsta
February 14, 2023 - Note: In summary, malloc() and new both can be used to allocate memory dynamically in C++, but new provides automatic memory management and does not require manual calculation of memory size, making it easier to use and less error-prone than ...
๐ŸŒ
Quora
quora.com โ€บ What-is-the-difference-between-malloc-and-new-in-C
What is the difference between 'malloc' and 'new' in C++? - Quora
Answer (1 of 7): [code ]malloc[/code] is just the C way of allocating memory. [code ]new[/code] is the C++ way of allocating memory, but has some added benefits. You can use [code ]malloc[/code] in C++, though I rarely see it done. [code ]new[/code] calls the appropriate constructor for the type,...
๐ŸŒ
Medium
medium.com โ€บ @Farhan11637 โ€บ new-vs-malloc-54cfd186d07b
New vs Malloc(). What is New | by Farhan Ahmad | Medium
October 19, 2024 - malloc() returns a void*, requiring you to cast it to the appropriate type (e.g., int*, float*). new: Returns a pointer of the type being allocated (e.g., int* if allocating memory for an integer).
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 3223239 โ€บ what-does-new-do-that-mallocrealloc-do-not-do-
What does 'new' do that malloc/realloc do not do ? | Sololearn: Learn to code for FREE!
Today vs code gave me this warning: ... realloc ? What does new do that realloc doesn't/can't do ?? ... Like malloc(), new allocates space in memory....
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ difference-between-new-and-malloc
Difference between new and malloc( )
Memory canโ€™t be initialized using this function. The memory allocated using malloc can be deallocated using free function.
๐ŸŒ
GameDev.net
gamedev.net โ€บ forums โ€บ topic โ€บ 79858-cc-new-and-delete-vs-malloc-and-free โ€บ 1403251
C/C++ new and delete vs. malloc and free - For Beginners - GameDev.net
December 7, 2001 - You should use new and delete in c++ because it''s type safe. Using malloc you need to force a type on the object because it returns a void pointer, and you can''t assign that to other types. You also don''t have to figure out the size of what you''re creating.
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ cplusplus-programming โ€บ 117435-new-delete-vs-malloc-free.html
New/delete vs malloc/free
You mean aside from the fact that new/delete calls the constructor/destructor for the objects it creates, which malloc/free doesn't. Sure, beside that fact, they are pretty much the same. They both allocate memory and assign it to the pointer you give, and release the memory from a given pointer.
๐ŸŒ
Quora
quora.com โ€บ C-Why-is-new-better-than-good-old-trustworthy-malloc
C++: Why is new better than good old trustworthy malloc()? - Quora
Answer (1 of 5): By using [code ]new[/code], the [code ]malloc[/code] is invoked under the hood to make the memory allocations anyway. However, using [code ]new[/code] the main difference is that a constructor of the objects you want to create is called, either when is about built-in or user-defi...