Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

does malloc(sizeof(Class1)) allocate the same size of memory as new Class1?

For any class, say "Class1"

Does cpp standard guarantee that

malloc(sizeof(Class1)) 

allocate the same size of memory as allocated by new operator?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new Class1

>Solution :

The non-array new expression calls an operator new to allocate storage with a size argument exactly equal to sizeof of the object type. (Note that this is not necessarily true for the array version of new.)

How an operator new obtains storage is less clear. operator new overloads and replacements can be defined by the program and are free to obtain the storage in whatever way suits them.

The default implementation of the global operator new which is provided by the compiler/standard library has no requirements placed on it either in regards to how it acquires the memory. It doesn’t need to use std::malloc, for example.

In practice, I think implementations usually simply call std::malloc with the same size argument to acquire the memory.


So the answer depends on what exactly you mean by "allocate". In the standard language the allocation is the call to operator new which is guaranteed to be called with the same size argument as in your malloc call.

If by "allocate" you mean what calls to std::malloc will happen, then the answer is that the standard doesn’t place any requirements on whether or not std::malloc calls happen and with what arguments.

If you go down even further, it is also completely up to the implementation how std::malloc itself obtains memory. Of course that will strongly depend on the operating system and so on.


Aside from this allocation, the constructor call to Class1 may also cause more memory allocations to occur (but not for the storage of the object created by new itself), which can never happen with malloc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading