Correct use of Realloc

前端 未结 4 1760
刺人心
刺人心 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:25

    This code snippet is wrong.

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

    If the call of realloc returns NULL then the previous value of the pointer a is lost. So there can be a memory leak because it will be impossible to free the memory allocated by the call of malloc.

    If just to write

    if(realloc(a, 100) == NULL) //Deal with the problem
    

    then in turn the returned pointer of the call of the realloc can be lost.

    This code snippet

    int *oldPtr = malloc(10);
    int * newPtr = realloc(oldPtr, 100);
    if(newPtr == NULL) //deal with problems
    else oldPtr = newPtr;
    

    is correct. However if to write

    int *oldPtr = malloc(10);
    if(realloc(oldPtr, 100) == NULL)  //deal with problems
    //else not necessary, oldPtr has already been reallocated and has now 100 elements
    

    then again the returned pointer of the call of realloc can be lost.

    From the description of realloc in the C Standard (7.22.3.5 The realloc function)

    4 The realloc function returns a pointer to the new object (which may have (or may not have - added by me) the same value as a pointer to the old object, or a null pointer if the new object could not be allocated.

提交回复
热议问题