Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need to use malloc in C++?

Tags:

c++

c

qt

qt4

If I can create a QString in C++ like:

QString s = "my string"; // or,
QString *s = new QString("my string");

Then, when will I event need to use malloc?

like image 487
Roman Avatar asked Dec 09 '22 04:12

Roman


1 Answers

You never need to use malloc in C++.

Ok, now that I've said never, one exception is when you are using C code that for some reason or another takes ownership of a block of memory you give it and later calls free on a pointer to that memory to deallocate it.

I have never seen that before (I don't usually use C libraries and I don't know how common that scenario is), it's just a contrived situation that I can think of where using malloc would not be optional, because it's undefined behaviour to call free on a piece of memory created by new.

like image 112
Seth Carnegie Avatar answered Dec 24 '22 12:12

Seth Carnegie