Yeah, you’d have to write your own. It’s so simple it’s really silly, but its performance will scream in comparison to simply using malloc() and free() all the time....
static const int maxParticles = 1000;
static Particle particleBuf[maxParticles]; // global static array
static Particle* headParticle;
void initParticleAllocator()
{
Particle* p = particleBuf;
Particle* pEnd = &particleBuf[maxParticles-1];
// create a linked list of unallocated Particles
while (p!=pEnd)
{
*((Particle**)p) = p+1;
++p;
}
*((Particle**)p) = NULL; // terminate the end of the list
headParticle = particleBuf; // point 'head' at the 1st unalloc'ed one
}
Particle* ParticleAlloc()
{
// grab the next unalloc'ed Particle from the list
Particle* ret = headParticle;
if (ret)
headParticle = *(Particle**)ret;
return ret; // will return NULL if no more available
}
void ParticleFree(Particle* p)
{
// return p to the list of unalloc'ed Particles
*((Particle**)p) = headParticle;
headParticle = p;
}
You could modify the approach above to not start with any global static array at all, and use malloc() at first when the user calls ParticleAlloc(), but when Particles are returned, don't call free() but instead add the returned ones to the linked list of unalloc'ed particles. Then the next caller to ParticleAlloc() will get one off the list of free Particles rather than use malloc(). Any time there are no more on the free list, your ParticleAlloc() function could then fall back on malloc(). Or use a mix of the two strategies, which would really be the best of both worlds: If you know that your user will almost certainly be using at least 1000 Particles but occasionally might need more, you could start with a static array of 1000 and fall back on calling malloc() if you run out. If you do it that way, the malloc()'ed ones do not need special handling; just add them to your list of unalloc'ed Particles when they come back to ParticleFree(). You do NOT need to bother calling free() on them when your program exits; the OS will free the process'es entire memory space, so any leaked memory will clear up at that point.
I should mention that since you question was tagged "C" and not "C++", I answered it in the form of a C solution. In C++, the best way to implement this same thing would be to add "operator new" and "operator delete" methods to your Particle class. They would contain basically the same code as I showed above, but they override (not overload) the global 'new' operator and, for the Particle class only, define a specialized allocator that replaces global 'new'. The cool thing is that users of Particle objects don't even have to know that there's a special allocator; they simply use 'new' and 'delete' as normal and remain blissfully unaware that their Particle objects are coming from a special pre-allocated pool.