C ++ - 调用std :: vector的.clear()时访问violoation

时间:2016-01-26 20:08:31

标签: c++ visual-c++ mfc stdvector access-violation

我正在Visual Studio C ++ MFC应用程序中实现XLSX电子表格阅读器,并且在多次执行时遇到访问冲突错误:

First-chance exception at 0x7720e39e in VCT.exe: 0xC0000005: Access violation reading location 0x02bdddab.
Unhandled exception at 0x7720e39e in VCT.exe: 0xC0000005: Access violation reading location 0x02bdddab.
The program '[1756] VCT.exe: Native' has exited with code -1073741819 (0xc0000005).

奇怪的是,根据我的其余代码,这可以在函数被调用两次,三次或更多之后发生......这让我觉得它与时序有关,但我只是让单线程运行。我的另一个(更现实的)假设是它是一种未定义的行为。这使得调试特别困难。令我困惑的是为什么在多次调用函数后会发生此访问冲突。

已添加至问题:

每次单击按钮时,我都会调用函数getVectorAllIP。点击几下(拨打getVectorAllIP)后,我就会在第一次拨打mm_XLSXReader.xlsxGetCellOffset时收到访问冲突错误。

vector<CString> CVCTDlg::getVectorAllIP(string ipName){

    CString CSIP1;

    vector<CString> VCSIPAddresses;

    XLSXReader mm_XLSXReader;
    mm_XLSXReader.reloadFile();
    mm_XLSXReader.setFilePath(XLSX_FILE_PATH);

    for(int i = 0; i < m_vectorStrHostname.size(); i++)
    {
        CSIP1="";
        for(int iOffset = 0; iOffset < 4; iOffset++)
        {

            CSIP1.Append(mm_XLSXReader.xlsxGetCellOffset(ipName, i, iOffset).c_str());
            if(iOffset != 3)
            {
                CSIP1.Append(".");
            }
        }

        if(CSIP1 != "...")
        {

            VCSIPAddresses.push_back(CSIP1);

        }else{
            VCSIPAddresses.push_back("");
        }

    }

    return VCSIPAddresses;

}

xlsxGetCellOffset内,readSheetXml内发生访问冲突错误。

string XLSXReader::xlsxGetCellOffset(string columnName, int id, int offset)
{
    string contentToReturn;
    id++;

    if(!m_bFileInMemory)
    {
        if(openm_XLSXReader())
        {
            readSharedStringsXml();
            readSheetXml();

            closem_XLSXReaders();

            m_bFileInMemory = true;
        }
    }

    for(int i = 0; i < m_header.size(); i++)
    {
        if(m_header.at(i) == columnName && m_header.size() > i + offset)
        {
            if(m_sheetContent.size() > id)
            {
                if(m_sheetContent.at(id).size() > i)
                {
                    contentToReturn = m_sheetContent.at(id).at(i+offset);
                }
            }
        }
    }

    return contentToReturn;
}

在结束时的清算过程中发生访问冲突。具体来说是columnContent.clear()。如果我删除了columnContent.clear(),则会在下一行tParameterColumn.clear()发生。

void XLSXReader::readSheetXml()
{
    if(m_m_XLSXReader)
    {
        int error = unzLocateFile(m_m_XLSXReader, SHEET_NAME, 0);
        if(error == UNZ_OK)
        {
            error = unzOpenCurrentFile(m_m_XLSXReader);
            if(error == UNZ_OK)
            {
                int readingStatus = 0;
                char readBuffer[BUFFERSIZE];
                string file;
                int indexValue;
                //Reading File
                do
                {
                    readingStatus = unzReadCurrentFile(m_m_XLSXReader, readBuffer, BUFFERSIZE);
                    file.append(readBuffer, readingStatus);
                }while(readingStatus > 0);


                //Sort Data
                vector<string> rowContent;
                rowContent = findXmlTagsContent(file, "row");

                unsigned int iHdrSize;
                m_header.clear();

                vector<string> columnContent;
                vector<string> tParameterColumn;
                vector<string> rParameterColumn;
                vector<string> tmpRow;
                for(int i = 0 ; i < rowContent.size(); i++)
                {

                    columnContent=findXmlTagsContent( rowContent.at(i), "c"); 
                    rParameterColumn=findXmlParameterInTag(rowContent.at(i), "c", "r");
                    tParameterColumn=findXmlParameterInTag(rowContent.at(i), "c", "t");
                    if(i==0){
                        iHdrSize = columnContent.size();
                    }

                    //Should be equal
                    if(columnContent.size() == tParameterColumn.size())
                    {
                        unsigned int iFilledColumns = 0;
                        for(int j = 0 ; j < columnContent.size(); j++)
                        {               

                            int columnNumber = 0;

                            if(!rParameterColumn.at(j).empty())
                            {
                                columnNumber = columnLetter2Int(rParameterColumn.at(j));
                            }

                            vector<string> value;
                            value = findXmlTagsContent(columnContent.at(j), "v");

                            if(value.size()>1){
                                value.clear();
                                value.push_back("");
                            }

                            //Header Reading
                            if( i == 0)
                            {
                                //Fill empty spaces in excel sheet with ""
                                for(int a = 1; a < columnNumber-iFilledColumns; a++)
                                {
                                    m_header.push_back("");
                                }
                                iFilledColumns=m_header.size();

                                //link to sharedString
                                if(tParameterColumn.at(j) == "s")
                                {
                                    indexValue = atoi(value.at(0).c_str());
                                    string tmpStr = m_sharedString.at(indexValue);
                                    m_header.push_back(tmpStr);
                                }
                                //Value
                                else
                                {   
                                    m_header.push_back(value.at(0));
                                }
                            }
                            // Content Reading
                            else
                            {
                                ////Fill empty spaces in excel sheet with ""
                                for(int a = 1; a < columnNumber-iFilledColumns; a++)
                                {
                                    tmpRow.push_back("");
                                }
                                iFilledColumns=tmpRow.size();
                                //link to sharedString

                                if(tParameterColumn.at(j) == "s")
                                {
                                    indexValue = atoi(value.at(0).c_str());
                                    tmpRow.push_back(m_sharedString.at(indexValue));
                                }
                                //Value
                                else
                                {
                                    if(value.size() != 0)
                                    {
                                        tmpRow.push_back(value.at(value.size()-1));
                                    }
                                    else
                                    {
                                        tmpRow.push_back("");
                                    }
                                }

                            }
                            iFilledColumns++;
                        }
                        for(int k=0;k<iHdrSize-iFilledColumns;k++){
                            tmpRow.push_back("");
                        }
                        m_sheetContent.push_back(tmpRow);
                        tmpRow.clear();
                        columnContent.clear();
                        tParameterColumn.clear();
                        rParameterColumn.clear();

                    }
                }       
            }
        }
    }
}

仅供参考,m_m_XLSXReader会在openm_XLSXReader内调用的xlsxGetCellOffset调用时实例化。这是供您参考:

bool XLSXReader::openm_XLSXReader()
{
    //Uncompress .xlsx
    m_m_XLSXReader = unzOpen(m_strXLSXPath.c_str());

    if(m_m_XLSXReader){
        return true;
    }
    return false;
}

希望有人可以指出一些明显的错误,因为我开始质疑我的理智:)谢谢。

2 个答案:

答案 0 :(得分:1)

这个循环:

do
{
    readingStatus = unzReadCurrentFile(m_m_XLSXReader, readBuffer, BUFFERSIZE);
    file.append(readBuffer, readingStatus);
} while (readingStatus > 0);

会将最后一个读取块追加两次,最有可能产生无效的XML。 我不知道您使用哪个库来读取XML(除了这个问题之外找不到findXmlTagsContent的任何引用),以及它的弹性如何,但怀疑它可能表现不佳垃圾。另外,您没有检查任何可能的错误...

底线是:尝试阅读你的文件:

while ((readingStatus = unzReadCurrentFile(m_m_XLSXReader, readBuffer, BUFFERSIZE)) > 0)
    file.append(readBuffer, readingStatus);

另外,如果返回为负数(错误代码),您打算做什么?

答案 1 :(得分:0)

好的,谢谢大家的帮助和建议。

弗拉德,你的建议确实让我以更合乎逻辑的方式思考,然后我发现问题与实际的XLSX阅读完全无关。

简单的解释是,当我点击关闭XLSX阅读器的按钮时,我会在此之前修改Windows注册表。在递归删除某些注册表项的过程中,会发生某种类型的内存损坏,这只有在我获得访问冲突时才会反映出来。我修复了我的注册码,现在问题已经解决了。

如果有人对递归删除注册表项的实际问题感兴趣,请继续阅读......

我正在使用代码递归删除注册表项及其子项:

Deleting a Key with Subkeys

#include <windows.h>
#include <stdio.h>
#include <strsafe.h>

//*************************************************************
//
//  RegDelnodeRecurse()
//
//  Purpose:    Deletes a registry key and all its subkeys / values.
//
//  Parameters: hKeyRoot    -   Root key
//              lpSubKey    -   SubKey to delete
//
//  Return:     TRUE if successful.
//              FALSE if an error occurs.
//
//*************************************************************

BOOL RegDelnodeRecurse (HKEY hKeyRoot, LPTSTR lpSubKey)
{
    LPTSTR lpEnd;
    LONG lResult;
    DWORD dwSize;
    TCHAR szName[MAX_PATH];
    HKEY hKey;
    FILETIME ftWrite;

    // First, see if we can delete the key without having
    // to recurse.

    lResult = RegDeleteKey(hKeyRoot, lpSubKey);

    if (lResult == ERROR_SUCCESS) 
        return TRUE;

    lResult = RegOpenKeyEx (hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);

    if (lResult != ERROR_SUCCESS) 
    {
        if (lResult == ERROR_FILE_NOT_FOUND) {
            printf("Key not found.\n");
            return TRUE;
        } 
        else {
            printf("Error opening key.\n");
            return FALSE;
        }
    }

    // Check for an ending slash and add one if it is missing.

    lpEnd = lpSubKey + lstrlen(lpSubKey);

    if (*(lpEnd - 1) != TEXT('\\')) 
    {
        *lpEnd =  TEXT('\\');
        lpEnd++;
        *lpEnd =  TEXT('\0');
    }

    // Enumerate the keys

    dwSize = MAX_PATH;
    lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
                           NULL, NULL, &ftWrite);

    if (lResult == ERROR_SUCCESS) 
    {
        do {

            StringCchCopy (lpEnd, MAX_PATH*2, szName);

            if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) {
                break;
            }

            dwSize = MAX_PATH;

            lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
                                   NULL, NULL, &ftWrite);

        } while (lResult == ERROR_SUCCESS);
    }

    lpEnd--;
    *lpEnd = TEXT('\0');

    RegCloseKey (hKey);

    // Try again to delete the key.

    lResult = RegDeleteKey(hKeyRoot, lpSubKey);

    if (lResult == ERROR_SUCCESS) 
        return TRUE;

    return FALSE;
}

//*************************************************************
//
//  RegDelnode()
//
//  Purpose:    Deletes a registry key and all its subkeys / values.
//
//  Parameters: hKeyRoot    -   Root key
//              lpSubKey    -   SubKey to delete
//
//  Return:     TRUE if successful.
//              FALSE if an error occurs.
//
//*************************************************************

BOOL RegDelnode (HKEY hKeyRoot, LPTSTR lpSubKey)
{
    TCHAR szDelKey[MAX_PATH*2];

    StringCchCopy (szDelKey, MAX_PATH*2, lpSubKey);
    return RegDelnodeRecurse(hKeyRoot, szDelKey);

}

void __cdecl main()
{
   BOOL bSuccess;

   bSuccess = RegDelnode(HKEY_CURRENT_USER, TEXT("Software\\TestDir"));

   if(bSuccess)
      printf("Success!\n");
   else printf("Failure.\n");
}

如果我在要删除的密钥中有值,那么一切都按预期工作。如果我的密钥里面有一个子密钥,它们就被删除了,但我开始讨论上面的问题了。

因此,例如,这被删除而不会让我感到痛苦,

[KeyName1]
--> SOME_DWORD
--> SOME_STRING

这一次确实给我带来了很多痛苦,

[KeyName2]
--> SOME_DWORD
--> SOME_STRING
--> [SubKeyName]
-----> SOME_DWORD
-----> SOME_STRING