Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

You can't allocate a void pointer with C++'s operator new: you'll have to allocate an explicit type such as char or uint8_t:

char *p = new char[7];
uint8_t *q = new uint8_t[7];
...
delete [] p;
delete [] q;

Yes you can.
But depending on what you are doing there may be better techniques.

Can you update the question and tell us what you are trying to achieve. With more context a better solution could be provided.

An Example:
If you were dynamically allocating a buffer to read from a socket (because the size is not known at compile time). An alternative would be to use a vector and dynamically size that. You can then get a pointer to the inside of the buffer by taking the address of the first element.

Personally I would use a std::vector<char>. Not only do you get an arbitrary block of bytes (guaranteed to be contiguous), you get them in an RAII wrapper. Of course, there's no need to use any of std::vector's methods (aside from, maybe, resize()), but there's no penalty for that:

std::vector<char> buffer(7);
void* p = &buffer[0];

You could use a std::string, but std::string implies "this object contains characters that make sense when printed out," where a std::vector<char> implies "this object contains an arbitrary group of bytes."

I think you might be looking for Placement New.

new char[7];

Traditionally, char is a byte, though you might find some libraries that typedef a BYTE type.

You can do char* pBuffer = new char[7];, and since the sizeof(char) is 1 byte you can use it as a byte buffer. Also, remember to use delete[] (with []) when releasing the memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top