In what cases do I use malloc and/or new?

new c++
malloc vs new performance
malloc vs calloc
does new call malloc
what does new return in c++
can we use malloc and calloc in c++
why use malloc instead of new
free store vs heap

I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on something that was created with the new operator), but I'm not clear on when I should use malloc/ free and when I should use new/ delete in my real world programs.

If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.


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

malloc() vs new, Whenever a program needs memory to declare at run time we can use this function. new. new is an operator in C++ programming language, it is also used to  operator vs function: new is an operator, while malloc() is a function. return type: new returns exact data type, while malloc() returns void *. Failure Condition: On failure, malloc() returns NULL where as new throws bad_alloc exception. Memory: In case of new, memory is allocated from free store where as in malloc() memory allocation is done from heap.


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!

Difference between new and malloc() in C++, In C, you should use malloc and its family of functions (e.g., calloc, realloc, free). The new and delete operators are not available in C. In C++,  new is an operator in C++ and it calls the constructor. malloc is a function and does not. new returns an object of that type, malloc returns a void pointer. If malloc fails, it returns 0; if new fails, it throws an error. As an operator, new can be overridden, same as any other operator. Lastly, operators are faster than functions. I basically always use new.


From the C++ FQA Lite:

[16.4] Why should I use new instead of trustworthy old malloc()?

FAQ: new/delete call the constructor/destructor; new is type safe, malloc is not; new can be overridden by a class.

FQA: The virtues of new mentioned by the FAQ are not virtues, because constructors, destructors, and operator overloading are garbage (see what happens when you have no garbage collection?), and the type safety issue is really tiny here (normally you have to cast the void* returned by malloc to the right pointer type to assign it to a typed pointer variable, which may be annoying, but far from "unsafe").

Oh, and using trustworthy old malloc makes it possible to use the equally trustworthy & old realloc. Too bad we don't have a shiny new operator renew or something.

Still, new is not bad enough to justify a deviation from the common style used throughout a language, even when the language is C++. In particular, classes with non-trivial constructors will misbehave in fatal ways if you simply malloc the objects. So why not use new throughout the code? People rarely overload operator new, so it probably won't get in your way too much. And if they do overload new, you can always ask them to stop.

Sorry, I just couldn't resist. :)

Learning programming: In what cases do I use malloc vs new?, //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  If you want raw memory, the equivalent to malloc would be operator new, e.g. void* buffer = ::operator new(100000); Although char's are basic types so don't do anything dangerous on construction or destruction, it's semantically more clear to use operator new than to use a char array object and then reuse its underlying storage for a different set of objects.


Always use new in C++. If you need a block of untyped memory, you can use operator new directly:

void *p = operator new(size);
   ...
operator delete(p);

In what cases do I use malloc and/or new?, malloc() The function malloc() is used to allocate the requested size of using namespace std; int main () { int *ptr1 = NULL; ptr1 = new int; float  malloc allocates memory, while new allocates memory AND calls the constructor of the object you're allocating memory for. So, unless you're restricted to C, you should never use malloc, especially when dealing with C++ objects. That would be a recipe for breaking your program. Also the difference between free and delete is quite the same.


Use malloc and free only for allocating memory that is going to be managed by c-centric libraries and APIs. Use new and delete (and the [] variants) for everything that you control.

malloc() vs new() in C/C++, To return a pointer to a type other than void, use a type cast on the return By default, malloc does not call the new handler routine on failure to  malloc(), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with 'zero (0)' in case on int. delete and free() both can be used for 'NULL' pointers.


malloc, Your re-implement of malloc() must allocate heap memory using the sbrk() call. You should not edit this file, as we will replace it with a new, clean copy when we run This test case is the first test case that will break by using our simple "bad  Answers: new is an operator, whereas malloc () is a fucntion. new returns exact data type, while malloc () returns void * (pointer of type void). malloc (), memory is not initialized and default value is garbage, whereas in case of new, memory is initialized with default value, like with ‘zero (0)’ in case on int.


MP2: My, oh, my, oh, malloc!, C dynamic memory allocation refers to performing manual memory management for dynamic Still, there are several situations in which using new/delete is not applicable, such as garbage collection code or In the case of realloc it would have signaled that the original memory was not moved and freed, which again is​  1 it doesn't make much sense to return a non-null pointer, but so does malloc(0); the specification leaves this one open so a compiler builder may choose not to handle malloc(0) specifically, so that all the other mallocs are a nanosecond faster (because the check for 0 is ommited) – ammoQ Jan 25 '10 at 13:17 6 PJ Plauger (C Standard Committee member) in one of his articles said their were


C dynamic memory allocation, Every time a function declares a new variable, it is "pushed" onto the stack. Then every This is not the case for variables allocated on the heap. To allocate memory on the heap, you must use malloc() or calloc() , which are built-in C functions. If you fail to do this, your program will have what is known as a memory leak. 1) new est un opérateur , tandis que malloc() est une fonction . 2) new appelle constructeurs , tandis que malloc() ne l'appelle pas. 3) new renvoie type de données exactes , tandis que malloc() renvoie void * . 4) new ne renvoie jamais un nul (sera jeté sur l'échec) tandis que malloc() renvoie nul . 5) réallocation de la mémoire non