Difference

What is the Difference Between malloc , calloc , new
senexpertAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gurpreetsCommented:
The  malloc()function provides a simple,
general-purpose memory allocation package. The  malloc() function returns a pointer to a block of specified bytes suitably aligned for any use.

The calloc()function allocates space for an array of specified elements of specified size. The space is initialized to zeros.

The new() function does two things. It first allocates raw memory by calling malloc and then calls the constructor of the object.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mikeblasCommented:
gurpreets missed at least four very important differences:

First, new is an operator and not a function.

Second, memory allocated with new must be freed with delete.

Third, new is for C++ and can't be used in C, while malloc() and calloc() can be used in C or C++.

Fourth, new reports errors in a very different way than malloc() or calloc().

..B ekiM
0
yonatCommented:
Two more things about new:
1. You don't need to calculate the number of bytes to allocate - new does the math for you.
2. It's type safe - the returned pointer type matches the type of the allocated object, not void*.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.