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 withfree
.calloc
is likemalloc
but initializes the allocated memory with a constant (0). It needs to be freed withfree
.new
initializes the allocated memory by calling the constructor (if it's an object). Memory allocated withnew
should be released withdelete
(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
- Memory allocated from 'Free Store'.
- Returns a fully typed pointer.
new
(standard version) never returns aNULL
(will throw on failure).- Are called with Type-ID (compiler calculates the size).
- Has a version explicitly to handle arrays.
- Reallocating (to get more space) not handled intuitively (because of copy constructor).
- Whether they call
malloc
/free
is implementation defined. - Can add a new memory allocator to deal with low memory (
std::set_new_handler
). operator new
/operator delete
can be overridden legally.- Constructor / destructor used to initialize / destroy the object.
malloc
/ free
- Allocate / release memory
- Memory allocated from 'Heap'.
- Returns a
void*
. - Returns
NULL
on failure. - Must specify the size required in bytes.
- Allocating array requires manual calculation of space.
- Reallocating larger chunk of memory simple (no copy constructor to worry about).
- They will NOT call
new
/delete
. - No way to splice user code into the allocation sequence to help with low memory.
malloc
/free
can NOT be overridden legally.
Table comparison of the features:
Feature | new / delete | malloc / free |
---|---|---|
Memory allocated from | 'Free Store' | 'Heap' |
Returns | Fully typed pointer | void* |
On failure | Throws (never returns NULL ) | Returns NULL |
Required size | Calculated by compiler | Must be specified in bytes |
Handling arrays | Has an explicit version | Requires manual calculations |
Reallocating | Not handled intuitively | Simple (no copy constructor) |
Call of reverse | Implementation defined | No |
Low memory cases | Can add a new memory allocator | Not handled by user code |
Overridable | Yes | No |
Use of constructor / destructor | Yes | No |
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 rowi
columnj
should beprintf(" %5d ", *(arr + i * col + j));
multiply
should returnarr
anddisplay()
should be called in themain
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 aconst
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
Detecting If Computer Is Idle Based on Mouse and Keyboard Interactions
External Library Throws Undefined Reference Errors in Qt Creator
How to Correctly Interpose Malloc Allowing for Ld_Preload Chaining
C Compiler Error from Standard Headers - Undefined C++ Definitions
Get Memory Overflow Caused by a Memory Leak and the Application Keep Running and Allocating
How to Get Memory Information on Linux System
Why Is Nonblocking Socket Writable Before Connect() or Accept()
Linux X11 - Global Keyboard Hook
C++ Delete Vector, Objects, Free Memory
What Is the Default Constructor for C++ Pointer
Array Initialization Use Const Variable in C++
Why Shared_From_This Can't Be Used in Constructor from Technical Standpoint
How to Overload Operators for Built-In Types Like Int or Float
C++ System() Not Working When There Are Spaces in Two Different Parameters
How to Implode a Vector of Strings into a String (The Elegant Way)