How to handle realloc when it fails due to memory?

后端 未结 8 836
不思量自难忘°
不思量自难忘° 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:40

    The standard technique is to introduce a new variable to hold the return from realloc. You then only overwrite your input variable if it succeeds:

    tmp = realloc(orig, newsize);
    if (tmp == NULL)
    {
        // could not realloc, but orig still valid
    }
    else
    {
        orig = tmp;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题