How to handle realloc when it fails due to memory?

后端 未结 8 894
不思量自难忘°
不思量自难忘° 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;
    }
    

提交回复
热议问题