8

i came across some code, that uses allocate extensively. For example,

char* recordDate = allocate<char>(20)

I have never used allocate before and hence the question, what is the difference between malloc and allocate?

One difference that i can tell, although i am unclear about its advantage, is that, malloc gives raw memory, where as it seems like allocate will give raw memory, but i dont have to cast the pointer to a specific type.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
Jimm
  • 8,165
  • 16
  • 69
  • 118
  • 2
    What exactly is `allocate`? – user541686 Jun 13 '13 at 15:13
  • 1
    @Mehrdad It is part of std. See std::allocator::allocate http://en.cppreference.com/w/cpp/memory/allocator/allocate – Cory Klein Jun 13 '13 at 15:17
  • 3
    @CoryKlein That's not `allocate<>`, that's `std::allocator::allocate` (and I cannot image that *"code extensively using it"* always being part of an allocator implementation, especially this `recordData` example). – Christian Rau Jun 13 '13 at 15:35
  • 1
    @CoryKlein: Wait, what? Which overload of `allocate` in `std::allocator` takes in a type parameter like `char`, as shown in `allocate`? – user541686 Jun 13 '13 at 17:08

3 Answers3

3

From allocate documentation:

Allocates n * sizeof(T) bytes of uninitialized storage by calling ::operator new(std::size_t), but it is unspecified when and how this function is called.

Also, from this question, you can see that new and malloc lead to different results.

Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93
3

It appears that the difference is that with allocate you only have to give the number of items you want rather than the total size, and the return type is automatically cast to the correct type for you.

In C++ you should almost never use either, but prefer new which will call appropriate constructors.

Mark B
  • 95,107
  • 10
  • 109
  • 188
0

Conceptually, these two functions do exactly the same thing. The only time you'll see a difference is if you start "looking at the inside of the function" or you run out of memory (malloc will return NULL, since allocate calls ::new, it will throw a bad_alloc exception).

I think it's "better C++" to use allocate (if for no other reason than "You don't have to cast allocate).

Having said that, using ::new T[elements] would be the normal way in C++, and outside of places where you have a passed in allocator, this is what you should be doing.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227