How to handle realloc when it fails due to memory?

后端 未结 8 891
不思量自难忘°
不思量自难忘° 2020-11-27 19:18

Question says it all but here is an example:

typedef struct mutable_t{
    int count, max;
    void **data;
} mutable_t;


void pushMutable(mutable_t *m, voi         


        
8条回答
  •  离开以前
    2020-11-27 19:54

    There's also another subtle error that can come from realloc. The memory leak coming from returned NULL pointer is rather well known (but quite rare to stumble upon). I had in my program a crash once in a while that came from a realloc call. I had a dynamic structure that adjusted its size automatically with a realloc resembling this one:

    m->data = realloc(m->data, m->max * sizeof(void*)); 
    

    The error I made was to not check for m->max == 0, which freed the memory area. And made from my m->data pointer a stale one.

    I know it's a bit off-topic but this was the only real issue I ever had with realloc.

提交回复
热议问题