Search code examples
c++mallocbstralloca

How do I use _malloca instead of _alloca in Win32 C++ project?


I'm updating an old C++ DLL project. For one of the exported functions there's

BSTR __stdcall j2cs( const long lJulian, int bDMY, BSTR sDelim ) {
    USES_CONVERSION;
    int iDay, iMonth;
    long lYear;
    char chDate[20];
    char chInt[10];
    char * cDelim = W2A( sDelim );

The W2A macro is defined as

#define W2A(lpw) (\
    ((_lpw = lpw) == NULL) ? NULL : (\
        (_convert = (static_cast<int>(wcslen(_lpw))+1), \
        (_convert>INT_MAX/2) ? NULL : \
        ATLW2AHELPER((LPSTR) alloca(_convert*sizeof(WCHAR)), _lpw, _convert*sizeof(WCHAR), _acp))))

Visual Studio 2019 flags the W2A macro with the following compiler warning

Warning C6255   _alloca indicates failure by raising a stack overflow exception.  Consider using _malloca instead.  

How would I make the suggested change to the W2A macro? Or should I just ignore the warning?

LATER

My USES_CONVERSION macro is defined as

#define USES_CONVERSION int _convert = 0; (_convert); UINT _acp = ATL::_AtlGetConversionACP() /*CP_THREAD_ACP*/; (_acp); LPCWSTR _lpw = NULL; (_lpw); LPCSTR _lpa = NULL; (_lpa)

Solution

  • W2A can't be changed to using malloc. You have to add free in all places where W2A used. The ideal alternative is std::vector in place of _alloca.

    Update the macro USES_CONVERSION, so it contains std::vector<WCHAR> _buffer; and update the macro W2A:

    #define USES_CONVERSION int _convert = 0; (_convert); std::vector<WCHAR> _buffer; (_buffer); UINT _acp = ATL::_AtlGetConversionACP() /*CP_THREAD_ACP*/; (_acp); LPCWSTR _lpw = NULL; (_lpw); LPCSTR _lpa = NULL; (_lpa)
    
    #define W2A(lpw) (\
        ((_lpw = lpw) == NULL) ? NULL : (\
            (_convert = (static_cast<int>(wcslen(_lpw))+1), \
            (_convert>INT_MAX/2) ? NULL : \
            (_buffer.resize(_convert), \
            ATLW2AHELPER((LPSTR) _buffer.data(), _lpw, _convert*sizeof(WCHAR), _acp)))))