Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Can I mix C-style and C++ style allocation and deallocation?

0
10 Posted

Can I mix C-style and C++ style allocation and deallocation?

0

Yes, in the sense that you can use malloc() and new in the same program. No, in the sense that you cannot allocate an object with malloc() and free it using delete. Nor can you allocate with new and delete with free() or use realloc() on an array allocated by new. The C++ operators new and delete guarantee proper construction and destruction; where constructors or destructors need to be invoked, they are. The C-style functions malloc(), calloc(), free(), and realloc() doesn’t ensure that. Furthermore, there is no guarantee that the mechanism used by new and delete to acquire and release raw memory is compatible with malloc() and free(). If mixing styles works on your system, you were simply “lucky” – for now. If you feel the need for realloc() – and many do – then consider using a standard library vector.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.