Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between malloc and allocate

Tags:

c++

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.

like image 864
Jimm Avatar asked Jun 13 '13 15:06

Jimm


People also ask

Is malloc memory allocated?

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.

What is the difference between the malloc and Colloc?

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.

How do I allocate with malloc?

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.

Is it better to use malloc () or calloc ()?

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.


1 Answers

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.

like image 59
md5 Avatar answered Oct 03 '22 12:10

md5