+ Reply to Thread
Results 1 to 2 of 2

Thread: What is difference between new vs malloc?

  1. #1

    What is difference between new vs malloc?

    Hi All,

    What is difference between new vs malloc?

    Regards,

  2. #2
    Hi,

    'new' operator:
    a. new is like an operator in C++
    b. new does not reqire casting to target type
    c. new calls constructor of the type specified.
    d. new does not required size of the data to be allocated. It requires type to be allocated.
    e. 'new' operator can be overloaded as per user requirement.
    f. Memory allocated by 'new' has to be free using 'delete'.
    g. new can throw exception.

    'malloc' operator:
    a. malloc is like a function.
    b. malloc returns void * so it requires casting.
    c. It does not call constructor.
    d. It requires size in bytes to allocate memory
    e. Malloc cannot be overloaded
    f. Memory allocated by 'malloc' has to be free using 'free'.
    g. malloc returns NULL on failure.

    Example:

    Code:
    void UseNewAndMalloc()
    {
    	void *pMalloc = malloc(100) ;
    	free(pMalloc) ;
    
    	int *pNew = new int ;
    	delete pNew ;
    
    	int *pNewArray = new int[10] ;
    	delete []pNewArray ;
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts