退出代码 -1073741510 在 bool if 语句处

Exit code -1073741510 at bool if statement

本文关键字:if 语句 bool 代码 -1073741510 退出      更新时间:2023-10-16

我正在编写一个程序,提示用户输入.txt文件,然后将ifstream对象和整数数组传递给函数 - count_letters(ifstream &, int *arrayInts(。

然后,该函数从 ifstream 对象中读取每个字符,并存储来自 a-z 的字符频率(不区分大小写(。每个字符都传递给一个 bool 函数,该函数检查它是否为非字母字符。为了可读性,我注释了字母Vect和checkVect向量,因为它们很长。

此时,我的程序退出执行。即使我可以看到返回为"true",也不会执行 for 循环。函数结束前的循环打印出 arrayInt 的内容也永远不会执行。

void count_letters(std::ifstream &fileIn, int *arrayInt)
{
    char c;                 // character variable to read from  fileIn
    bool cACReturn;         // charArrayCheck return value
    int aICount = 0;        // count for arrayInt in for loop
    std::vector<char> alphabetVect {// characters 'a' - 'z'};
    while (fileIn.get(ch))
    {
        tempCh = ch;
        cACReturn = charArrayCheck(ch);
        std::cout << "cACReturn = " << cACReturn << std::endl;
        while (1)
        {
            // If ch is an alphabetical character
            if (cACReturn == true)
            {
                for (size_t i = 0; i < alphabetVect.size(); (i + 2))
                {
                    if (ch == alphabetVect[i] || ch == alphabetVect[i + 1])
                    {
                        std::cout << "success" << std::endl;
                        arrayInt[aICount]++;
                    }
                    aICount++;
                }
            }
            else
            {
                std::cout << "false" << std::endl;
            }
        }
    }
    for (int i = 0; i < 26; i++)
    {
        std::cout << "In count_letter letterArray[" << i << "] = " << arrayInt[i] << std::endl;
    }
}

下面是 charArrayCheck 函数:

bool charArrayCheck(char charIn)
{
    std::vector<char> checkVect {// non alphabet characters};
    for (size_t i = 0; i < checkVect.size(); i++)
    {
        if (charIn == checkVect[i])
        {
            std::cout << "false in charArrayCheck" << std::endl;
            return false;
        }
        else
        {
            if (i == (checkVect.size() -1))
            {
                return true;
            }
            else
            {
                continue;
            }
        }
    }
}

感谢您的任何和所有帮助。

问题可能是这一行:

            for (size_t i = 0; i < alphabetVect.size(); (i + 2))

因为它从不重新分配i,这是一个无限循环。 aICount不断递增,最终arrayInt[aICount]++数组边界之外的访问。这会导致未定义的行为,并且由于导致的所有内存损坏,程序崩溃。

它应该是:

            for (size_t i = 0; i < alphabetVect.size(); i += 2)