Sunday, September 03, 2006

DYNAMIC MEMORY ALLOCATION

Whenever we require n bytes of memory using new or malloc, we actually use up at least n bytes of memory, because typically the memory manager must add some overhead to your request. There are two common considerations that affect this overhead are housekeeping overhead and chunk size overhead.

The housekeeping overhead: In a general-purpose or not fixed-size allocation scheme, the memory manager will have to somehow remember how big each block is so that it later knows how much memory to release when we call delete or free. Typically the manager remembers the block size by storing that value at the beginning of the actual block it allocates and then giving you a pointer to "your" memory that's offset past the housekeeping information, this means it has to allocate extra space for that value, which could be a number as big as the largest possible valid allocation and so is typically the same size as a pointer. When freeing the block, the memory manager will just take the pointer we give it, subtract the number of housekeeping bytes and read the size, and then perform the de-allocation.

Of course, fixed-size allocation schemes (i.e., ones that return blocks of a given known size) don't need to store such overhead because they always know how big the block will be.

The chunk size overhead: Even when we don't need to store extra information, a memory manager will often reserve more bytes than you asked for, because memory is often allocated in certain-sized chunks.
For one thing, some platforms require certain types of data to appear on certain byte boundaries (e.g., some require pointers to be stored on 4-byte boundaries) and either break or perform more slowly if they don't. This is called alignment, and it calls for extra padding within, and possibly at the end of, the object's data. Even plain old built-in C-style arrays are affected by this need for alignment because it contributes to sizeof(struct).

No comments: