Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation in C++

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?

like image 868
user132349 Avatar asked Jul 02 '09 15:07

user132349


2 Answers

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.

like image 147
CB Bailey Avatar answered Oct 02 '22 19:10

CB Bailey


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.

like image 37
dma Avatar answered Oct 02 '22 20:10

dma