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

If I can create a QString in C ++, for example:

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

Then, when will I need the malloc event?

+4
source share
4 answers

You never need to use malloc in C ++.

Well, now, as I already said, the exception is when you use C code, which for some reason takes responsibility for the memory block that you give it, and then calls the free pointer to this memory to free it.

I have never seen this before (I usually do not use C libraries, and I don’t know how common this script is), it’s just a far-fetched situation where I can think about where using malloc will not be optional, because this undefined behavior causes free on a piece of memory created by new .

+11
source

In C ++, you almost never need to use malloc .

+2
source

Never!

malloc allocates uninitialized memory. You rarely have to do this in C ++. Most of the time you create and destroy objects with new and delete .

There are several situations where you need to allocate unintelliged memory, for example, when implementing containers with dynamic size, such as std::vector and boost::optional . But then the C ++ path should not use malloc and free , but rather

 void* p = operator new(1000); ... operator delete(p); 
+1
source

C ++ mainly handles allocation and deallocation for you, unlike C.

In other words, you do not need to use malloc for your example.

0
source

Source: https://habr.com/ru/post/1385460/


All Articles