gpt4 book ai didi

正确使用 Realloc

转载 作者:行者123 更新时间:2023-12-01 07:17:44 25 4
gpt4 key购买 nike

这是我被教导使用的方式 realloc() :

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

那不是多余的吗?我不能做这样的事情吗? :
if(realloc(a, 100) == NULL) //Deal with the problem

对于我发现的其他 realloc 示例也是如此,例如:
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可能会返回 NULL如果请求无法满足(在这种情况下,原始缓冲区保留在原位)。因此,您希望将返回值保存到与原始值不同的指针变量中。否则,您可能会用 NULL 覆盖原始指针。并失去对该缓冲区的唯一引用。

例子:

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44789295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com