Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "new" and "malloc" and "calloc" in C++? [duplicate]

What is the difference between "new" and "malloc" and "calloc" and others in family?

(When) Do I need anything other than "new" ?

Is one of them implemented using any other?

like image 701
Łukasz Lew Avatar asked Oct 08 '22 09:10

Łukasz Lew


People also ask

What are the differences between malloc () and calloc () in C?

malloc() function creates a single block of memory of a specific size. calloc() function assigns multiple blocks of memory to a single variable.

What is the difference between malloc and realloc?

The malloc() and realloc() functions are part of dynamic memory; malloc() is used for the memory allocation and realloc() is used for the reallocation of the memory.


2 Answers

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.
like image 66
mmx Avatar answered Oct 14 '22 04:10

mmx


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

like image 21
Brian R. Bondy Avatar answered Oct 14 '22 03:10

Brian R. Bondy