Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C memory management

Name: Anonymous 2011-02-12 5:42

Hey /prog, I'm teaching myself C by writing a roguelike and I noticed that C uses manual memory management for creating objects in the heap. I was wondering if the C-gods could lend me some advice on how to proceed with this:

I want to write a roguelike with thousands of NPCs, every NPC is a really small piece of data which does not contain any pointers (position, stats, behavior... probably ends up being a few bytes). NPCs would spawn and die constantly. How would I go about managing the memory for this?

• malloc and free individual NPCs
• Boehm-Demers-Weiser conservative garbage collector
• malloc a big chunk of memory and build some kind of memory manager on top of it (are there techniques for this?)

Please advice.

Name: Anonymous 2011-02-21 10:29

funny to see your own dead threads resurrected... who the fuck is >>58? also, here's the lastest version of the code:

[#]
struct mem_pool
{
    unsigned int slot_size; // the size of each object in the pool
    unsigned int pool_size; // the number of objects in the pool
    unsigned int slots_left; // space left in the pool
    void* pool;
    void* ptr;
};

void mp_init(struct mem_pool* mp, unsigned int slot_size, unsigned int pool_size)
{
    mp->slots_left = pool_size;
    mp->slot_size = slot_size;
    mp->pool = malloc(pool_size*slot_size);
    if(mp->pool == NULL)
    {
        fprintf(stderr, "Out of memory, exiting\n");
        exit(1);
    }
    mp->ptr = mp->pool;
    memset(mp->pool, 0, pool_size*slot_size);
}

void* mp_alloc(struct mem_pool* mp)
{
    if (mp->slots_left == 0)
        return NULL;
   
    int* current = mp->ptr;
    if ( *current == 0)
        mp->ptr += mp->slot_size;
    else
        mp->ptr = (void*) *current;

    return (void*) current;
}

void mp_free(struct mem_pool* mp, void* slot)
{
    memcpy( slot, mp->ptr, sizeof(void*));
    mp->ptr = slot;
    mp->slots_left++;
}
[/#]

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List