gpt4 book ai didi

realloc - 如果它失败, realloc 会释放前一个缓冲区吗?

转载 作者:行者123 更新时间:2023-12-03 10:00:30 29 4
gpt4 key购买 nike

如果 realloc 失败并返回 NULL 是前一个缓冲区被释放还是保持不变?我没有在手册页中找到那条特定的信息,我不确定该怎么做。如果内存被释放,那么双重释放可能会有风险。如果没有,就会发生泄漏。

最佳答案

不,不是的。这方面经常让我恼火,因为你不能只使用:

if ((buff = realloc (buff, newsize)) == NULL)
return;

如果您想在失败时释放原始代码,请在您的代码中。相反,您必须执行以下操作:
if ((newbuff = realloc (buff, newsize)) == NULL) {
free (buff);
return;
}
buff = newbuff;

当然,我理解在失败时保持原始缓冲区完整的基本原理,但我的用例已经足够多,以至于我通常编写自己的函数来处理这种情况,例如:
// Attempt re-allocation. If fail, free old buffer, return NULL.

static void *reallocFreeOnFail (void *oldbuff, size_t sz) {
void *newbuff = realloc (oldbuff, sz);
if (newbuff == NULL) free (oldbuff);
return newbuff;
}

// Attempt re-allocation. If fail, return original buffer.
// Variable ok is set true/false based on success of re-allocation.

static void *reallocLeaveOnFail (void *oldbuff, size_t sz, int *ok) {
void *newbuff = realloc (oldbuff, sz);
if (newbuff == NULL) {
*ok = 0;
return oldbuff;
}

*ok = 1;
return newbuff;
}

C11 标准中的相关部分指出(我的斜体):

7.20.3.4 The realloc function

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

关于realloc - 如果它失败, realloc 会释放前一个缓冲区吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1607004/

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