正确使用 Realloc [英] Correct use of Realloc

查看:58
本文介绍了正确使用 Realloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我被教导使用 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

对于我发现的其他 realloc 示例也是如此,例如:

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;

我不能这样做吗?:

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

推荐答案

realloc 返回一个指向调整大小的缓冲区的指针;此指针值可能与原始指针值不同,因此您需要将该返回值保存在某处.

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 可能会返回 NULL(在这种情况下,原始缓冲区保留在原处).出于这个原因,您希望将返回值保存到与原始不同 指针变量中.否则,您可能会用 NULL 覆盖原始指针并丢失对该缓冲区的唯一引用.

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.

示例:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆