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 8:10

>>4
This isn't a terrible idea, but do document the practice since code like this is a little unclear about intentions:

struct NPC { /* whatever */ };
void del_npc(NPC *npc) {
    int i;
   
    for(i=0; (int)npc[i +1] != 0; i++);
    if( i != 0 ) memcpy(npc, &npc[i], sizeof(struct NPC));
    memset(&npc[i], 0, sizeof(struct NPC));
}


The convention here is that NPC will deref to an int which evaluates to zero. It's better to use a struct member to indicate that it's the last item on the list but this code will work with whatever your struct looks like (assuming it works at all, I haven't tested it.)

This assumes a fixed size array, which may or may not have been malloc'd. Adding an NPC to the end works similarly, find the first entry on the list that derefs to 0 -- but you'll have to guard against exhausting the list. There's also a subtle bug: if you do not null terminate the list, it will continue searching past the end of the array whenever the list is full.

I'd sooner use a nonserial format for this kind of thing because of the possibility of errors above. Alternatively you could just mark individual NPCs as "free" when deleting and skip them when walking the list.

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