Best way to handle memory allocation in C?

后端 未结 12 1748
春和景丽
春和景丽 2021-01-31 11:58

I think I\'ve got a good grasp on how to handle memory in C++ but doing it in C is different I\'m a bit off.

In C++ I\'ve got constructors and destructors, I\'ve got the

12条回答
  •  孤城傲影
    2021-01-31 12:19

    I'm not quite sure what you're asking, but C is pretty straightforward:

    struct Foo *f0 = malloc(sizeof(*f));   // alloc uninitialized Foo struct
    struct Foo *f1 = calloc(1,sizeof(*f)); // alloc Foo struct cleared to all zeroes
    
    //You usually either want to clear your structs using calloc on allocation, or memset. If 
    // you need a constructor, just write a function:
    Foo *Foo_Create(int a, char *b)
    {
       Foo *r = calloc(1,sizeof(*r));
       r->a = a;
       r->b = strdup(b);
       return r;
    }
    
    Here is a simple C workflow with arrays:
    struct Foo **foos = NULL;
    int n_foos = 0;
    ...
    for(i = 0; i < n_foos; ++i)
    {
       struct Foo *f = calloc(1,sizeof(*f));
       foos = realloc(foos,sizeof(*foos)*++n_foos); // foos before and after may be different
       foos[n_foos-1] = f;
    }
    

    If you get fancy, you can write macros to help:

    #define MALLOCP(P) calloc(1,sizeof(*P)) // calloc inits alloc'd mem to zero
    

    A couple of points:

    • malloc, calloc, realloc, etc. all use free(), so managing these things is easy. Just be consistant.
    • performance for mallocs can be slow. Someone posted a link on this above. These days fast multi-threaded allocations is key, see tcmalloc et al. You probably don't have to worry about this.
    • on a modern virtual memory architecture, malloc will almost never fail unless you are out of virtual address space. If this happens, switch to 64bit ;)
    • Make sure you're using a system that has bounds checking, wiped free values, leak tracking and all that good stuff (see valgrind, win32 debug heap, etc.)

提交回复
热议问题