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-12 17:48


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

#define MEM_SIZE 1024
#define MEM_TYPE int

MEM_TYPE* mem = NULL;
int mem_chunks = 0;
int mem_free = 0;
int mem_index = 0;

typedef union mem_block
{
    int next_block;
    MEM_TYPE value;
} mem_block;

void grow_pool()
{
    // printf( "chunks: %d\n", mem_chunks);
    mem_chunks++;
    mem_free = MEM_SIZE;
    mem = realloc(mem,mem_chunks * MEM_SIZE * sizeof(MEM_TYPE));
   
    if(mem == NULL)
    {
        fprintf(stderr, "Out of memory, exiting\n");
        exit(1);
    }
   
        memset(mem + (mem_chunks-1) * MEM_SIZE * sizeof(MEM_TYPE),
        0xFF,
        MEM_SIZE * sizeof(MEM_TYPE));
}

int store(MEM_TYPE data)
{
    if ( mem_free-- == 0) grow_pool();
   
    int old_index = mem_index;
    int current = mem[mem_index];
   
    if ( current == 0xFFFFFFFF)
    {
        mem[mem_index++] = data;
        return (mem_index-1);
    }
    else
    {
        mem[mem_index] = data;
        mem_index = current;
        return old_index;
    }
}

void unstore(idx)
{
    mem[idx] = mem_index;
    mem_index = idx;
    mem_free++;
}

int main()
{
    grow_pool();
    store(345);
    int i = store(4038);
    store(12);
    printf( "%d\n", mem[i]);
    unstore(i);
    printf( "%d\n", mem_free);
   
    for ( i = 0; i < 1100; i++) store(i);
    // segfault... WTF!!!!
}

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