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-13 9:36

no more segfaults!


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MEM_TYPE char
#define CHUNK_SIZE 12

union mem_block
{
    unsigned int next_free;
    MEM_TYPE val;
};

union mem_block* mem_pool;

#define mem_(idx) mem_pool[idx].val

unsigned int mem_chunks = 0;
unsigned int mem_blocks_left = 0;
unsigned int mem_index = 0;

void grow_pool()
{
    mem_chunks++;
    mem_blocks_left = CHUNK_SIZE;
   
    mem_pool = realloc(mem_pool, mem_chunks * CHUNK_SIZE * sizeof(union mem_block));
   
    if(mem_pool == NULL)
    {
        fprintf(stderr, "Out of memory, exiting\n");
        exit(1);
    }
   
    memset(mem_pool + (mem_chunks-1) * CHUNK_SIZE,
        0xFF,
        CHUNK_SIZE * sizeof(union mem_block));
}


int store(MEM_TYPE data)
{
    if ( mem_blocks_left == 0) grow_pool();
    mem_blocks_left--;
   
    int old_index = mem_index;
    union mem_block current = mem_pool[mem_index];
   
    if ( current.next_free == 0xFFFFFFFF)
    {
        mem_pool[mem_index++] = (union mem_block) data;
        return (mem_index-1);
    }
    else
    {
        mem_pool[mem_index] = (union mem_block) data;
        mem_index = current.next_free;
        return old_index;
    }
}

void unstore(unsigned int idx)
{
    mem_pool[idx] = (union mem_block) mem_index;
    mem_index = idx;
    mem_blocks_left++;
}

int main()
{
    grow_pool();
    int i;
    for ( i = 0; i < CHUNK_SIZE * 30; i++) store(i*2);
    for ( i = 0; i < CHUNK_SIZE * 30; i++) unstore(i);
    for ( i = 0; i < CHUNK_SIZE * 30; i++) store(i*2);
    int d = store(123);
    printf( "%d\n", mem_(d));
    exit(1);
}

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