Search code examples
c++stringpointersreverse-engineering

My helper function is returning an empty string


I'm writing some code for a game, and I'm attempting to write a helper function to return a string inside an object:

const char* getGhostName(GhostAI* ghostAI)
{
    if (ghostAI) {
        GhostInfo* ghostInfo = getGhostInfo(ghostAI);
        const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
        const char* name = il2cppi_to_string(ghostName).c_str();
        return name;
    }
    return "UNKNOWN";
}

And here is the il2cppi_to_string functions:

std::string il2cppi_to_string(Il2CppString* str) {
    std::u16string u16(reinterpret_cast<const char16_t*>(str->chars));
    return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);
}

std::string il2cppi_to_string(app::String* str) {
    return il2cppi_to_string(reinterpret_cast<Il2CppString*>(str));
}

When I call getGhostName, I end up with an empty string. Now I did get a warning from ReSharper which says:

Object backing the pointer will be destroyed at the end of the full-expression.

This is appearing on the following line inside getGhostName when calling il2cppi_to_string:

const char* name = il2cppi_to_string(ghostName).c_str();

I'm not entirely sure what this means or how I can modify the code to fix it. I absolutely hate working with strings in C++.


Solution

  • il2cppi_to_string() returns a temporary std::string, which will be destroyed at the end of the expression that calls il2cppi_to_string(). You are obtaining a const char* pointer to the data of that temporary std::string, which is what ReSharper is warning you about. Since the temporary std::string is destroyed before the return, that means getGhostName() is returning a dangling pointer to invalid memory.

    To fix this, change getGhostName() to return a std::string instead of a const char*:

    std::string getGhostName(GhostAI* ghostAI)
    {
        if (ghostAI) {
            GhostInfo* ghostInfo = getGhostInfo(ghostAI);
            const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
            return il2cppi_to_string(ghostName);
        }
        return "UNKNOWN";
    }