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 12:19

>>11
The example code was posted because it only took 3 lines of meat to point out what kinds of problems >>1 would probably run into given such advice.
All problems you've mentioned in >>7 stem from the brain-damaged idea of not using the list length. Reread it yourself, it's hilarious -- you've mentioned literally zero problems that could be present otherwise. Even the problem of unclear intentions pretty much doesn't exist if you write it correctly:
void delete_npc(struct NPC * npcs, int * length, int index)
{
    ASSERT(0 <= index && index < length);
    *length--;
    if (index < *length)
        memcpy(npcs[index], npcs[*length], sizeof(NPC));
}

If the advice in >>4 is to be useful it presumes the list will be walked at some point and the procedure can be folded in at that time.
No, you intend walk it each time you delete or add an NPC. That can't be "folded" into anything. Because if you store the length then you don't need to walk the list at all.
Please do stick with C++ though. Linus and I will know to disregard your every opinion.
Hahaha, "Linus and I", I'm afraid if Linus saw you he would seriously consider switching to C++. You really, really suck at programming. Like, no Indian sweatshop would hire you, you're that bad. Seriously. If you think about becoming a professional programmer, please reconsider, you are not cut for it, you'll waste a lot of time, energy and money, both your own and of the people who'd have to deal with you.

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