c++memory-managementmalloc

Is it safe to use _malloca with std::unique_ptr with a custom deleter to _freea?


_malloca from the Windows SDK does a stack allocation when the requested size is small and a heap allocation when it exceeds a certain size, because of that, _malloca requires a call to _freea. I'd like to use RAII to avoid having to do manual deletion and have the deletion be automatically handled at the end of scope.

My assumption is that as long as I do the _malloca call in the scope of the function containing the unique_ptr, it should be fine, as long as I'm not wrapping that call inside a constructor or another class. Would there be any problems with this?

It would look something like this:

#include <memory>
#include <malloc.h>

struct StackPtrDeleter {
    void operator()(void* ptr) const {
        _freea(ptr);
    }
};

template <typename T>
using StackPtr = std::unique_ptr<T, StackPtrDeleter>;

void function() {
    StackPtr<char> buffer(static_cast<char*>(_malloca(256))); 

    // do stuff with buffer
    // ...
    // _freea automatically called at end of scope
}

Solution

  • The intended usage looks safe as long as you obey the restrictions around use of _malloca in exception handlers.

    To avoid passing such a unique_ptr around accidentally, you could delete the copy-constructor and assignment of the deleter:

    struct StackPtrDeleter {
        void operator()(void* ptr) const {
            _freea(ptr);
        }
        StackPtrDeleter() = default;
        StackPtrDeleter(const StackPtrDeleter&) = delete;
        void operator=(const StackPtrDeleter&) = delete;
    };