i came across some code, that uses allocate
extensively. For example,
char* recordDate = allocate<char>(20)
I have never used allocate before and hence the question, what is the difference between malloc and allocate?
One difference that i can tell, although i am unclear about its advantage, is that, malloc gives raw memory, where as it seems like allocate will give raw memory, but i dont have to cast the pointer to a specific type.
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block. To hold this returned pointer, we must create a variable. The pointer should be of same type used in the malloc statement.
1. malloc() function creates a single block of memory of a specific size. calloc() function assigns multiple blocks of memory to a single variable. 2.
ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
malloc() doesn't initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which will usually mean the values you read will be garbage. calloc() allocates the memory and also initializes every byte in the allocated memory to 0.
From allocate
documentation:
Allocates
n * sizeof(T)
bytes of uninitialized storage by calling::operator new(std::size_t)
, but it is unspecified when and how this function is called.
Also, from this question, you can see that new
and malloc
lead to different results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With