How to handle realloc when it fails due to memory?

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

    The strategy about what to do when realloc() fails depends upon your application. The question is too generic to be answered for all possible cases.

    Some other notes:

    Never do:

    a = realloc(a, size);
    

    If realloc() fails, you lose the original pointer, and realloc() does not free() the original memory, so you will get a memory leak. Instead, do:

    tmp = realloc(a, size);
    if (tmp)
        a = tmp;
    else
        /* handle error */
    

    Second point I want to make is minor and may not be that critical, but it's good to know about it anyway: increasing the memory to be allocated by a factor f is good. Let's say you malloc() n bytes first. Then you need more memory, so you realloc() with size n×f. Then you need more memory, so you need n×f2 bytes. If you want realloc() to use the space from the previous two memory blocks, you want to make sure that n×f2 ≤ n + n×f. Solving this equation, we get f≤ (sqrt(5)+1)/2 = 1.618 (the Golden ratio). I use a factor of 1.5 most of the times.

提交回复
热议问题