C Memory Management

前端 未结 12 1181
旧时难觅i
旧时难觅i 2020-11-30 16:54

I\'ve always heard that in C you have to really watch how you manage memory. And I\'m still beginning to learn C, but thus far, I have not had to do any memory managing rela

12条回答
  •  抹茶落季
    2020-11-30 17:34

    (I'm writing because I feel the answers so far aren't quite on the mark.)

    The reason you have to memory management worth mentioning is when you have a problem / solution that requires you to create complex structures. (If your programs crash if you allocate to much space on the stack at once, that's a bug.) Typically, the first data structure you'll need to learn is some kind of list. Here's a single linked one, off the top of my head:

    typedef struct listelem { struct listelem *next; void *data;} listelem;
    
    listelem * create(void * data)
    {
       listelem *p = calloc(1, sizeof(listelem));
       if(p) p->data = data;
       return p;
    }
    
    listelem * delete(listelem * p)
    {
       listelem next = p->next;
       free(p);
       return next;
    }
    
    void deleteall(listelem * p)
    {
      while(p) p = delete(p);
    }
    
    void foreach(listelem * p, void (*fun)(void *data) )
    {
      for( ; p != NULL; p = p->next) fun(p->data);
    }
    
    listelem * merge(listelem *p, listelem *q)
    {
      while(p != NULL && p->next != NULL) p = p->next;
      if(p) {
        p->next = q;
        return p;
      } else
        return q;
    }
    

    Naturally, you'd like a few other functions, but basically, this is what you need memory management for. I should point out that there are a number tricks that are possible with "manual" memory management, e.g.,

    • Using the fact that malloc is guaranteed (by the language standard) to return a pointer divisible by 4,
    • allocating extra space for some sinister purpose of your own,
    • creating memory pools..

    Get a good debugger... Good luck!

提交回复
热议问题