Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 954
Khanh H Avatar asked Oct 26 '25 05:10

Khanh H


1 Answers

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;
};
like image 182
j6t Avatar answered Oct 27 '25 19:10

j6t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!