Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
For my Bulk Allocator function how can I returns a pointer to a contiguous block of memory of at least size bytes, similar to malloc()


extra 8 bytes will be given to a header for our bulk allocated objects in the same fashion as pool allocated objects thus being freed easily

bulk_alloc() function returns a pointer to a contiguous block of memory similar to malloc().


What I have tried:

I have tried adding 8 bytes to the argument taken by the bulk allocator function. Then using pointer math to get past that and return that metadata.
Posted
Updated 21-Apr-20 5:51am

1 solution

Here is one way this can be done :
C++
void * Allocator( size_t amount )
{
    size_t desired = amount + sizeof( AllocationHeader );
    size_t allocAmount = std::max( desired, MinimumAllocationAmount );
    unsigned char * p = (unsigned char *)GetSomeMemory( allocAmount );
    p += sizeof( AllocationHeader );
    return p;
}
This is just pointer arithmetic, as you mentioned. The key is to cast it to a pointer of a type that is one byte long. Otherwise the arithmetic will be skewed - adding 1 will not offset the pointer by one byte.

In the example, the AllocationHeader is the header you mentioned, MinimumAllocationAmount is some minimum amount if you want to avoid allocating 1 or 2 bytes at a time, and GetSomeMemory is whatever you want to use to get memory - calloc, new, custom, etc...

Microsoft's allocator, in debug mode, puts a header and trailer around each allocation with special bytes in them and they test for corruption by checking those special bytes. If they differ then memory was overrun or underrun.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900