Search code examples
c++stringluareturn-valuedangling-pointer

I don't understand why I have a dangling pointer


I have written this method:

std::string Utils::GetFileContents(const char* filePath)
{
    std::ifstream in(filePath, std::ios::binary);

    if (in)
    {
        std::string contents;
        in.seekg(0, std::ios::end);
        contents.resize(in.tellg());
        in.seekg(0, std::ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
        return(contents);
    }

    throw(errno + " ERROR: Could not open file.");
}

In another method, I have these instructions:

lua_State* state = luaL_newstate();

const char* code = Utils::GetFileContents(path).c_str();
luaL_dostring(state, code);

lua_close(state);

If you run your debugger in the previous method, you get a dangling pointer at the code variable. I do not understand why.

I found a way to make this work - to basically store code in a std::string and then change the next line to luaL_dostring(state, code.c_str());.

It doesn't make sense to me, as in both cases, code is stored as a const char*.


Solution

  • The function returns an object of the type std::string

    std::string Utils::GetFileContents(const char* filePath)
    

    You are assigning a pointer with the address of the first character of the returned temporary string

    const char* code = Utils::GetFileContents(path).c_str();
    

    After this declaration the returned temporary object will be destroyed. So the pointer code is invalid and using it in the next call

    luaL_dostring(state, code);
    

    invokes undefined behavior.

    You could write for example

    std::string code = Utils::GetFileContents(path);
    luaL_dostring(state, code.c_str());