我编写了一个使用 HeapAlloc() 和 HeapFree() 连接字符串的函数,我想检查这些函数的返回值。但是,如果分配失败,我必须再次尝试分配直到它起作用。怎么做?
我将此问题与 this one 联系起来.
void add_to_buffer(LPTSTR* buffer, LPCTSTR msg) {
// Determine new size
int newSize = 0;
// Allocate new buffer
if (*buffer == NULL)
newSize = _tcsclen(msg) + 1;
else
newSize = _tcslen(*buffer) + _tcsclen(msg) + 1;
// Do the copy and concat
if (*buffer == NULL)
{
*buffer = (LPTSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, newSize * sizeof(*buffer));
_tcsncpy_s(*buffer, newSize, msg, _tcsclen(msg));
}
else
{
*buffer = (LPTSTR)HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *buffer, newSize * sizeof(*buffer));
_tcsncat_s(*buffer, newSize, msg, _tcsclen(msg));
}
}
最佳答案
However, if allocation fail, I must try again to allocate until it works. How to do that?
不,如果分配失败,一切都结束了。那时你应该终止这个过程。根本没有理由相信后续分配会成功。一次又一次的尝试是没有用的,电脑不是那样工作的。一旦你进入低内存状态,你就可以预料到左边、右边和中间的问题。最安全的做法是中止。
现在,可以编写能够在低内存状态下生存的程序。但这需要非常小心地设计和处理内存分配。它要求程序的所有部分都遵循该设计。你的程序不是那种性质的。
关于c - 分配失败怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24265679/