Search code examples
c++functionlptstr

static LPTSTR variable loses value after function execution


I'm writing C++ dll on Visual studio 2013. My dll should read parameters from ini file. So, I've created a function for this purpose (ReadConnectionSettings()). My static variable serverIP gets value properly during the function working, however once the function complete running the variable (serverIP) loses its value. What seems to be the problem?

static LPTSTR   serverIP = _TEXT("");

void ReadConnectionSettings()
{
    TCHAR url[256];

    GetPrivateProfileString(_T("Connection"), _T("Url"), _T(""), url, 256, NameOfIniFile);

    serverIP = url;

}

Solution

  • You are pointing the pointer serverIP at stack memory url.

    This goes out of scope when the function exits, so your pointer is left pointing to junk.

    What you could do is make serverIP a buffer instead, and copy the URL into it. Then it would persist.

    That is:

     static TCHAR serverIP[256] = _TEXT("");
    

    Then:

     _tcsnccpy(serverIP, url, 255);
    

    Or as @DavidOtano suggested, you could keep your existing serverIP pointer, and use:

     serverIP = _tcsdup(url);
    

    But if you do this, you're dynamically allocating memory, so will need to remember to call:

     free(serverIP);
    

    when you no longer need it, to avoid a memory leak.