On Sun, Oct 19, 2025 at 10:04 PM Yan-Jie Wang <[email protected]> wrote:
> +    str=new(::std::nothrow) char[mbSize];

It seems that ConvertBSTRToString calls `operator new[](size_t)` to
allocate memory rather than calling the nothrow version.

    #include <comutil.h>
    #include <comdef.h>
    #include <string.h>
    #include <wchar.h>
    #include <stdio.h>
    #include <new>

    void *operator new[](std::size_t size) {
        printf("operator new[](size_t) called, %zx\n", size);
        void *ptr = malloc(size);
        if (!ptr) throw std::bad_alloc();
        return ptr;
    }

    void* operator new[](std::size_t count, const std::nothrow_t& tag )
    {
        printf("operator new[](size_t,std::nothrow&) called, %zx\n", count);
        void *ptr = malloc(count);
        if (!ptr) return nullptr;
        return ptr;
    }

    void operator delete[](void *ptr) {
        free(ptr);
    }

    int main(void) {
        try {
            constexpr unsigned int len = 0x30000000;
            ::BSTR b1 = (BSTR) malloc((len + 1) * sizeof(wchar_t));

            if (!b1) throw std::bad_alloc();

            ::wmemset(b1, L'a', len);
            b1[len] = 0;
            ::printf("       b1  = %p\n", b1);

            char* s1 = ::_com_util::ConvertBSTRToString(b1);
            ::printf("       s1  = %p\n", s1);
            ::printf("strlen(s1) = %zd (expecting %d)\n", ::strlen(s1), len);

            delete[] b1;
            delete[] s1;
        } catch (::_com_error& e) {
            ::printf("com error  = %s, code = 0x%lx\n",
e.ErrorMessage(), e.Error());
        } catch(::std::exception& e) {
            ::printf("exception  = %s\n", e.what());
        }
    }

This is the result:

    C:\msys64\home\yanjie>cl /nologo Test3.cpp /EHs /link comsuppw.lib
    Test3.cpp

    C:\msys64\home\yanjie>Test3.exe
        b1  = 0104E020
    operator new[](size_t) called, 30000001
    com error  = Not enough memory resources are available to complete
this operation., code = 0x8007000e

    C:\msys64\home\yanjie>

We may need to handle the exception in `ConvertBSTRToString` if we
would like to match the behavior of comsuppw.lib.


_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to