nsa
nsa

Reputation: 199

C++ Object Block Allocation vs Individual Allocation

what is the major difference with block allocation vs individual object allocation. let say

int iCount = 5;

int i = 0;
while(i < iCount)
{
  f = new foo();
 i++;
}

//////////////////
foo* f = new foo[iCount];

will that second method save some memory space for me?. i heard that every object we allocated surrounded by 16 admin bytes. so block allocation will only using one header guard. is it true?.

Upvotes: 4

Views: 421

Answers (2)

Sebastian Mach
Sebastian Mach

Reputation: 39089

Another very important difference is exception safety. In your code:

int iCount = 5;
int i = 0;
while(i < iCount)
{
    f = new foo();
    i++;
}

You must be very, very careful to not produce memory leaks with this; you definitely have to remember all foo to be able to properly clean this up in case of exception. If this code is in a constructor, it won't be enough to deallocate in your destructor, because if an exception is thrown, your object never comes to life and the destructor is not called. This further propagates to writing correct copy-construction and copy-assignment, each exception safe, etc.

Moral: Use standard containers, like vector, list, or deque (there are more).

//////////////////
foo* f = new foo[iCount];

This will at least destroy each constructed foo if an exception is thrown between allocating the first and last foo.

Of course you must take care that f will be properly deleted, especially if there are other throw-points the code that does this allocations.

Moral: Use standard containers. Manual memory management might seem trivial on the first glance, especially if you come from C, but it is non-trivial and critical to write exception-safe code.

Upvotes: 1

Griwes
Griwes

Reputation: 9029

Every allocation you do also allocates also allocation header (sometimes also some footer guard structure), which is dependent on algorithm used by your allocator. Here, you can find description of one of such algorithms.

When you allocate an array, the allocator (mainly malloc()) will be called with sizeof(element) * count as argument and will allocate entire array as one block, using one header struct, so it will introduce less memory overhead than allocating elements one-by-one (see note at bottom).

Anyway (as the question is tagged with ), good C++ programmer should avoid managing memory manually. For array, use Standard Library classes (vector, map, list etc.). Use RAII when possible, don't use raw pointers, but "smart" ones.


Note: everything I wrote here is entirely dependent on algorithm used, so that paragraph about array allocation may not apply to all possible memory allocation algorithms. So, direct answer to "what is the mayor difference between block allocation vs individual object allocation" is also algorithm-dependent.

Upvotes: 3

Related Questions