Correct use of Realloc

时光总嘲笑我的痴心妄想 提交于 2019-11-28 12:51:17
John Bode

realloc returns a pointer to the resized buffer; this pointer value may be different from the original pointer value, so you need to save that return value somewhere.

realloc may return NULL if the request cannot be satsified (in which case the original buffer is left in place). For that reason, you want to save the return value to a different pointer variable than the original. Otherwise, you risk overwriting your original pointer with NULL and losing your only reference to that buffer.

Example:

size_t buf_size = 0; // keep track of our buffer size

// ...

int *a = malloc(sizeof *a * some_size); // initial allocation
if (a)
    buf_size = some_size;

// ...

int *tmp = realloc(a, sizeof *a * new_size); // reallocation
if (tmp) {
    a = tmp;             // save new pointer value
    buf_size = new_size; // and new buffer size
}
else {
    // realloc failure, handle as appropriate
}

realloc on failure keeps the original pointer and size. realloc on success may not (and often does not) return the exact same pointer as the input.

So the proper solution is your third example.

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

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!