Search code examples
c++windowscstring

char* value gets corrupted during assignment


I have the following code , which gets a return value from a function as char*

cDestDrive = ReadFromRegistry(HKEY_CURRENT_USER,NDSPATH,szDestPathRoot);

I am able to read the value inside cDestDrive till the time I am assigning it. The moment I am assigning it:

 CString strServerAddress = cDestDrive;

the value of cDestDrive gets changed (corrupted) and I am not able to get the value in CString strServerAddres any Idea why this is happening.

Edit: Code to Read from Registry

char* CNDSShellExtender::ReadFromRegistry(HKEY hKey,LPCTSTR lpNDS,LPSTR lpRegKey)
{

        HKEY hRegKey=NULL;
        if(hKey==NULL || lpNDS==""||lpNDS==NULL||lpRegKey==""||lpRegKey==NULL)
            MessageBox(NULL,"Reading from Registry Failed!Invalid Path",
                                            _T("Network Drive Solution"),
                                                           MB_ICONERROR);

        LONG lOpenRes=RegOpenKey(hKey,lpNDS,&hRegKey);

        if (lOpenRes!=ERROR_SUCCESS ||lpNDS==NULL) 
            MessageBox ( NULL, "Can not Find Any Server to Connect",
                                            _T("NDSShellExtension"),
                                                     MB_ICONERROR );


        if(lOpenRes==ERROR_SUCCESS && lpNDS!=NULL)
        {
            TCHAR tSZValue[MAX_PATH] = {0};
            DWORD dwBufSize=MAX_PATH;
            LONG lCloseOut;
            LPBYTE lpStorage = reinterpret_cast<LPBYTE>(tSZValue);
            char* cpRegKeyVal=tSZValue;

            if (ERROR_SUCCESS == RegQueryValueEx(hRegKey,lpRegKey , 0, 0, (BYTE*)tSZValue, &dwBufSize))
                {
                    lCloseOut= RegCloseKey(hRegKey);
                    if (lCloseOut != ERROR_SUCCESS) 
                        MessageBox (NULL, "Registry Not Closed", 
                                        _T("NDSShellExtension"),
                                                 MB_ICONERROR );
                    return cpRegKeyVal;
                }
            else
            {
                    lCloseOut= RegCloseKey(hRegKey);
                    if (lCloseOut != ERROR_SUCCESS) 
                    MessageBox (NULL, "Registry Not Closed",
                                    _T("NDSShellExtension"),
                                             MB_ICONERROR );
                    return "";
            }
        }
            return "";
}

Solution

  • I believe you are returning a char* pointing to a an array that is allocated on the stack, i.e. this line:

    TCHAR tSZValue[MAX_PATH] = {0};
    

    followed by:

    char* cpRegKeyVal=tSZValue;
    

    This is dangerous, and you are experiencing first hand the end result!

    EDIT: why don't you directly assign to a CString in the function and return that?