C ++: equivalent to malloc new?

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

Hi guys, I'm noob in C ++, I want to know

memblock = (char *)malloc( currentByteLength); 

equivalently

memblock = new char[currentByteLength]

in C ++.

+5
source share
10 answers
memblock = (char *)malloc( currentByteLength); 

memblock = new char[currentByteLength];

Now there is no difference. But if you replace charwith int, then yes, there will be a difference, because in this case it mallocwill allocate memory by size currentByteLength, and it newwill allocate memory by size size(int) * currentByteLength. Therefore, be very careful.

Also, if the type referenced in the expression newis a user-defined type, then the default constructor will be called the currentByteLengthnumber of times to construct objects!

!

+5

. , , , char int, . . new , malloc - . , malloc C .

new ++, . malloc, : delete , malloc, free , new. . delete , new[] delete[] , new (, , , vector).

+4

malloc(), , free(). new[], , delete []. - .

, malloc -, .

, - - new , malloc .

+3

new free-store. malloc heap.

, . .

, , , . , , ( ). , .

++: http://www.gotw.ca/gotw/009.htm

+2

, malloc() - C, new - ++, , malloc() , NULL. - .

FAQ ++

+1

: , ++.

: , . , malloc() 'ed free()' ed, new 'ed delete d.

new , , .

++ new over malloc(), , C.

+1

:

  • (duh: P)
  • (malloc/free vs. operator new[]/operator delete[])
  • , . malloc 0, operator new[] .

. , :

  • -POD ( )
  • char - ( malloc), , operator new blob)

, ... ? ? , .

0

(/ ) , char 1 , .

memblock = (char *)malloc( currentByteLength * sizeof(char) ); 
0

,

memblock = new DATATYPE[length]

memblock = (DATATYPE*) malloc(length * sizeof(DATATYPE));

, , , .

, .

/, new/malloc delete/free .

new delete , / ( ), malloc free ( /).

0

( , char) :

  • How to clear memory at the end [first uses free, second uses delete]
  • The sizes may vary (if char is actually a wide 2-byte character, then the first only allocates enough space for currentByteLength bytes, and the new one allocates currentByteLength * 2 bytes)
  • malloc will fail by returning null, but the new one will throw an exception at runtime

FYI: you should always set the size check for malloc:

memblock = (char *)malloc( sizeof(char) * currentByteLength); 
0
source

All Articles