1 Answers
What is the difference between "malloc" and "new" in C++?
In C++, "malloc" and "new" are both used for dynamic memory allocation, but there are some key differences between them:
- Ownership: "malloc" is a function from the C programming language and simply allocates memory, while "new" is an operator in C++ that not only allocates memory but also constructs objects.
- Type Safety: "malloc" returns a void pointer (void*) which needs to be cast to the desired type, while "new" returns a pointer to the specific type being created.
- Memory Allocation: "malloc" does not call the constructor of the class for object creation, while "new" calls the constructor for object initialization.
- Size: "malloc" requires the size of memory to be specified manually, while "new" automatically calculates the size based on the type being created.
- Error Handling: "new" internally handles memory allocation failure using exceptions, while "malloc" returns NULL in case of failure.
Overall, "new" in C++ is considered more modern and safer for dynamic memory allocation compared to "malloc" in the C programming language.
Please login or Register to submit your answer