Correct use of Realloc

前端 未结 4 1771
刺人心
刺人心 2020-12-11 08:41

This is the way I\'ve been taught to use realloc():

int *a = malloc(10);
a = realloc(a, 100); // Why do we do \"a = .... ?\"
if(a == NULL) 
//De         


        
4条回答
  •  死守一世寂寞
    2020-12-11 09:33

    the correct way to call realloc is to save the return value in a temporary variable and check it for NULL. That way if realloc has failed, you haven't lost your original memory. For example:

    int *a, *b;
    a = malloc(10); 
    b = realloc(a, 100);
    if (b == NULL) {
        // handle error and exit
    }
    a = b;
    

    EDIT: Note that if the error handling doesn't exit, you should put the last line above, i.e. a = b; inside an else clause.

提交回复
热议问题