如果它失败, realloc 会释放前一个缓冲区吗? [英] Does realloc free the former buffer if it fails?
问题描述
如果 realloc 失败并返回 NULL 是前一个缓冲区被释放还是保持完整?我没有在手册页中找到那条特定的信息,我不确定该怎么做.如果内存被释放,那么双重释放可能会有风险.否则就会发生泄漏.
If realloc fails and returns NULL is the former buffer free'd or it is kept intact? I didn't found that particular piece of information in the man page and I'm quite unsure what to do. If memory is freed then double-free could be risky. If not then the leakage would occur.
推荐答案
不,它没有.这方面经常让我恼火,因为你不能只使用:
No, it does not. That aspect has often annoyed me since you can't just use:
if ((buff = realloc (buff, newsize)) == NULL)
return;
如果您想要在失败时释放原始代码,请在您的代码中.相反,您必须执行以下操作:
in your code if you want to free the original on failure. Instead you have to do something like:
if ((newbuff = realloc (buff, newsize)) == NULL) {
free (buff);
return;
}
buff = newbuff;
当然,我理解在失败时保持原始缓冲区完整的基本原理,但我的用例已经足够多,以至于我通常编写自己的函数来处理这种情况,例如:
Of course, I understand the rationale behind keeping the original buffer intact on failure but my use case has popped up enough that I generally code my own functions to handle that case, something like:
// 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 标准中的相关部分指出(我的斜体):
The relevant section in the C11 standard states (my italics):
7.20.3.4 realloc
函数
7.20.3.4 The
realloc
function
如果 ptr
是一个空指针,realloc
函数的行为类似于 malloc
函数指定尺寸.否则,如果 ptr
与之前返回的指针不匹配calloc
、malloc
或 realloc
函数,或者如果空间已被调用释放对于 free
或 realloc
函数,行为是未定义的.如果内存为新对象无法分配,旧对象不会被释放,其值不变.
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 会释放前一个缓冲区吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!