Is it possible to allocate an arbitrary memory block using the "new" operator? In C I can do it like "void * p = malloc(7);" - this will allocate 7 bytes if memory alignment is set to 1 byte. How to make the same in C++ with the new operator?
Arbitrary memory blocks can be allocated with operator new
in C++; not with the new
operator which is for constructing objects.
void* pBlock = ::operator new(7);
Such blocks can subsequently be freed with operator delete
.
::operator delete(pBlock);
Note that operator new
will allocated memory suitably aligned for any sort of object, so the implementation might not allocate exactly seven bytes and no more, but the same is (usually) true of malloc
. C clients of malloc
usually need aligned memory too.
Others have answered the question as written but I'd like to suggest sticking with malloc/free for such allocations.
new and delete are for allocating objects. They allocate the memory required and call constructors/destructors. If you know that you just need an arbitrary block of memory, using malloc and free is perfectly reasonable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With