1

I got a function in my class that returns a vector holding User and Pass read from an ini file.

Here's the code that reads it. I added outputs here for tests and it's reading it successfully.

vector<char*> Main::GetAccount(int i)
{
    vector<char*> LoginInfo;

    char szUser[13];
    char szPass[13];
    char szBuf[3];

    _itoa_s(i, szBuf, 10);

    GetPrivateProfileString(szBuf, "UserID", "User", szUser, 13, ".\\accounts.ini");
    GetPrivateProfileString(szBuf, "Pass", "Pass", szPass, 13, ".\\accounts.ini");

    if (strcmp(szUser, "User") == 0)
    {
        char szBuffer[80];
        sprintf_s(szBuffer, "Cannot read account %i.", i);
        Log(szBuffer);
        exit(EXIT_FAILURE);
    }
    else
    {
        LoginInfo.push_back(szUser);
        LoginInfo.push_back(szPass);

        return LoginInfo;
    }
}

And here is where I'm calling it, and where it goes wrong.

for (int i = 1; i < main->nBots + 1; i++)
{
    vector<char*> LoginInfo = main->GetAccount(i);

    char* szUser = LoginInfo[0];
    char* szPass = LoginInfo[1];

    cout << szUser << endl << szPass << endl;
}
Omar
  • 13
  • 2
  • [undefined behaviour](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – chris Jun 07 '14 at 00:45

1 Answers1

2

You're pushing back pointers to szUser and szPass into your Vector and return it after that. That's bad because szUser and szPass are local variables that'll get destroyed once you return from the function.

Now

vector<char*> LoginInfo = main->GetAccount(i);

char* szUser = LoginInfo[0];
char* szPass = LoginInfo[1];

here you access these pointers that are currently pointing to some garbage. This is undefined behavior. You should rethink what you want to do and might want to use std::string instead of handling char *'s.

By making it a vector<std::string> you'll get proper copies of the strings inside and don't have to worry about the ugly char *'s pointing to some location that went out of scope.

AliciaBytes
  • 7,300
  • 6
  • 36
  • 47