Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

c - Correct use of Realloc

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) 
//Deal with problem.....

Isn't that redundant? Can't i just do something like this? :

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

Same for other realloc examples i've found around, for example:

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

Can't i just do this instead? :

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...