user3748455
user3748455

Reputation: 13

What to do when an allocation fails?

I have written a function that concatenates strings by using HeapAlloc() and HeapFree() and I want to check the return of these functions. However, if allocation fails, I must try again to allocate until it works. How to do that ?

I link this question with 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));
    }
}

Upvotes: 0

Views: 91

Answers (1)

David Heffernan
David Heffernan

Reputation: 613163

However, if allocation fail, I must try again to allocate until it works. How to do that?

No, if an allocation fails, it's all over. At that point you should terminate the process. There's no reason at all to believe that a subsequent allocation will succeed. Trying again and again won't help, computers don't work like that. And once you have reached low-memory state, you can expect problems left, right and centre. The safest course of action is to abort.

Now, it is possible to write programs that can survive low-memory states. But this requires the memory allocation to be designed and handled very carefully. And it requires all parts of the program to adhere to that design. Your program is not of that nature.

Upvotes: 6

Related Questions