c++arraysmemorystrdupwcsdup

How do you best utilize wcsdup?


I'm writing code and a good portion of it requires returning wchar arrays. Returning wstrings aren't really an option (although I can use them) and I know I can pass a pointer as an argument and populate that, but I'm looking specifically to return a pointer to this array of wide chars. The first few iterations, I found that I would return the arrays alright, but by the time they are processed and printed, the memory would be overwritten and I would be left with gibberish. To fix this, I started using wcsdup, which fixed everything, but I'm struggling to grasp exactly what is happening, and thus, when it should be called so that it works and I leak no memory. As it is, I pretty much use wcsdup every time I return a string and every time a string is returned, which I know leaks memory. Here is what I'm doing. Where and why should I use wcsdup, or is there a better solution than wcsdup altogether?

wchar_t *intToWChar(int toConvert, int base)
{
    wchar_t converted[12];
    /* Conversion happens... */
    return converted;
}

wchar_t *intToHexWChar(int toConvert)
{
    /* Largest int is 8 hex digits, plus "0x", plus /0 is 11 characters. */
    wchar_t converted[11];

    /* Prefix with "0x" for hex string. */
    converted[0] = L'0';
    converted[1] = L'x';

    /* Populate the rest of converted with the number in hex. */
    wchar_t *hexString = intToWChar(toConvert, 16);
    wcscpy((converted + 2), hexString);

    return converted;
}

int main()
{
    wchar_t *hexConversion = intToHexWChar(12345);
    /* Other code. */

    /* Without wcsdup calls, this spits out gibberish. */
    wcout << "12345 in Hex is " << hexConversion << endl;
}

Solution

  • wchar_t *intToWChar(int toConvert, int base)
    {
        wchar_t converted[12];
        /* Conversion happens... */
        return converted;
    }
    

    This returns a pointer to a local variable.

    wchar_t *hexString = intToWChar(toConvert, 16);
    

    After this line, hexString will point to invalid memory and using it is undefined (may still have value or may be garbage!).

    You do the same thing with the return from intToHexWChar.

    Solutions:

    Note: you might also need to change to wcout instead of cout