Differencebetween "New" and "Malloc" and "Calloc" in C++

What is the difference between new and malloc and calloc in C++?

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.

Difference between malloc and calloc?

calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized.

For large allocations, most calloc implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS) or Windows VirtualAlloc) so it doesn't need to write them in user-space. This is how normal malloc gets more pages from the OS as well; calloc just takes advantage of the OS's guarantee.

This means calloc memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.) The effects are visible with performance experiments on Linux, for example.

Some compilers even can optimize malloc + memset(0) into calloc for you, but it's best to just use calloc in the source if you want zeroed memory. (Or if you were trying to pre-fault it to avoid page faults later, that optimization will defeat your attempt.)

If you aren't going to ever read memory before writing it, use malloc so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).


Embedded implementations of calloc may leave it up to calloc itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.

On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS), which is only enabled for some embedded kernels because it's insecure on a multi-user system.

What is the difference between new/delete and malloc/free?


new / delete

  • Allocate / release memory
    1. Memory allocated from 'Free Store'.
    2. Returns a fully typed pointer.
    3. new (standard version) never returns a NULL (will throw on failure).
    4. Are called with Type-ID (compiler calculates the size).
    5. Has a version explicitly to handle arrays.
    6. Reallocating (to get more space) not handled intuitively (because of copy constructor).
    7. Whether they call malloc / free is implementation defined.
    8. Can add a new memory allocator to deal with low memory (std::set_new_handler).
    9. operator new / operator delete can be overridden legally.
    10. Constructor / destructor used to initialize / destroy the object.

malloc / free

  • Allocate / release memory
    1. Memory allocated from 'Heap'.
    2. Returns a void*.
    3. Returns NULL on failure.
    4. Must specify the size required in bytes.
    5. Allocating array requires manual calculation of space.
    6. Reallocating larger chunk of memory simple (no copy constructor to worry about).
    7. They will NOT call new / delete.
    8. No way to splice user code into the allocation sequence to help with low memory.
    9. malloc / free can NOT be overridden legally.

Table comparison of the features:






























































Featurenew / deletemalloc / free
Memory allocated from'Free Store''Heap'
ReturnsFully typed pointervoid*
On failureThrows (never returns NULL)Returns NULL
Required sizeCalculated by compilerMust be specified in bytes
Handling arraysHas an explicit versionRequires manual calculations
ReallocatingNot handled intuitivelySimple (no copy constructor)
Call of reverseImplementation definedNo
Low memory casesCan add a new memory allocatorNot handled by user code
OverridableYesNo
Use of constructor / destructorYesNo

Difference between malloc and calloc in this case?

The only functional difference between allocating memory with malloc() and with calloc() for the same size, assuming the size computation is accurate, is the latter initializes the block to all bits 0, whereas the former does not.

All bits 0 means all int values in the array are initialized to 0.

The inner loop in the multiply function only increments the element at row i and column j, therefore the function relies on implicit initialization of the array elements to 0. calloc() does that, but not malloc() so you definitely need to use calloc().

Also note these remarks:

  • in display the computation for the offset of the matrix element at row i column j should be printf(" %5d ", *(arr + i * col + j));
  • multiply should return arr and display() should be called in the main function.
  • you should check for scanf(), malloc() and calloc()` failure
  • you should free allocated memory
  • pointer arguments to objects that are not modified by the function should be const qualified so the function can be called with a pointer to a const object.

Here is a modified version:

#include <stdio.h>
#include <stdlib.h>

int *getArray(int);
void display(const int *, int, int);
int *multiply(const int *, const int *, int);

int main() {
int n;
printf("enter dimension of square matrix:\n");
if (scanf("%d", &n) != 1)
return 1;
printf("\n now give input for the first array");
int *arr1 = getArray(n);
if (!arr1)
return 1;
display(arr1, n, n);
printf("\n now give input for the second array");
int *arr2 = getArray(n);
if (!arr2)
return 1;
display(arr2, n, n);
printf("\n\n\n");
int *arr = multiply(arr1, arr2, n);
if (!arr)
return 1;
printf("product of above matrices = \n\n");
display(arr, n, n);
free(arr1);
free(arr2);
free(arr);
return 0;
}

int *getArray(int n) {
int *arr = malloc(sizeof(int) * n * n);
if (arr == NULL)
return NULL;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (scanf("%d", (arr + i * n + j)) != 1) {
free(arr);
return NULL;
}
}
}
return arr;
}

void display(const int *arr, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf(" %5d ", *(arr + i * col + j));
}
printf("\n");
}
}

int *multiply(const int *arr1, const int *arr2, int n) {
int *arr = calloc((size_t)n * n, sizeof(int));
if (arr == NULL)
return NULL;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
*(arr + i * n + j) += (*(arr1 + i * n + k)) * (*(arr2 + k * n + j));
}
}
}
return arr;
}

Is there any performance difference between malloc and new in C++

You'd probably want to compare malloc() and free() with operator new() and operator delete() (and their array forms): This is how the memory is allocated independent from the construction of objects. The performance is likely to be very similar and it is quite likely that both approaches end up using the same memory pool: the C++ operators may be a thin wrappeer around malloc() and free() (but not the other way around: a user can safely implement operator new() and operator delete() in terms of malloc() and free()).

To determine the actual performance you'd obviously need to profile the two approaches in a reasonable way. Withouth having done so, I wouldn't expect much of a difference on most systems. Of course, the results will be specific to different systems.

What's the difference in C++ between new int[5] and malloc(5 * sizeof(int)) ?

As Mehrdad says in this question:

malloc allocates uninitialized memory. The allocated memory has to be released 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.

NOTE:- new is an operator, malloc is a function



Related Topics



Leave a reply



Submit