简体   繁体   中英

Run-Time Check Failure #2 - Stack around the variable 'ex' was corrupted

I get the run time exception;

Run-Time Check Failure #2 - Stack around the variable 'ex' was corrupted.

for the following piece of code.

DBConnPtr CDBConnector::GetConnectionInstance()
{
    if (m_pConn)
       return m_pConn;

    if (m_loginInfo.hostName.IsEmpty() || 
        m_loginInfo.portNumber == 0 || 
        m_loginInfo.userName.IsEmpty())
      return m_pConn;

    CString hostInfo(_T(""));
    hostInfo.Format("tcp://%s:%d", m_loginInfo.hostName, m_loginInfo.portNumber);
    sql::SQLString host = hostInfo;
    sql::SQLString user = m_loginInfo.userName;
    sql::SQLString pwd = m_loginInfo.userPwd;

    try
    {
        sql::Driver* pDriver = get_driver_instance();
        m_pConn = (DBConnPtr)pDriver->connect(host, user, pwd);
    }
    catch (sql::SQLException ex)
    {
    }
    //mysql_thread_end();

    return m_pConn;
}

Before moving sql::SQLString pwd = m_loginInfo.userPwd; outside the try block, it used to throw

Run-Time Check Failure #2 - Stack around the variable 'pwd' was corrupted.

Any ideas why? Im using mysql library and trying to catch SQLException that happens at the connect call.

EDIT

Output Window after typecasting every CString to LPCTSTR:

First-chance exception at 0x75B61D4D in MyApp.exe: Microsoft C++ exception: sql::SQLException at memory location 0x0493F8C0.
First-chance exception at 0x75B61D4D in MyApp.exe: Microsoft C++ exception: sql::SQLException at memory location 0x0493F8C0.
Unhandled exception at 0x005E18A5 in MyApp.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.

As MSDN points out: When you pass a character string as an optional argument, you must cast it explicitly as LPCTSTR.

Also, this article points out the consequence if you don't do so.

If the type SQLString can be cast to LPCTSTR, change this line:

hostInfo.Format("tcp://%s:%d", m_loginInfo.hostName, m_loginInfo.portNumber);

to:

hostInfo.Format(_T("tcp://%s:%d"), LPCTSTR(m_loginInfo.hostName), LPCTSTR(m_loginInfo.portNumber));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM