我一直在花时间学习更多关于加密和一般的密码。我开始研究一个控制台应用程序,以允许我加密或解密RSA类型的密码。C++未处理的异常:std :: bad_alloc
到目前为止,除了当我在要加密的字符串中包含字符“n”时,所有内容似乎都运行良好。出于某种原因,只有字母“n”强制应用程序中止。如果它本身是一串其他字符中的“n”,则无关紧要。它只是不喜欢“n”。
我仍然是一名学生,当谈到编码时,这只是我在C++中的第二个应用程序。
的错误:
Unhandled exception at 0x7743C42D in RSA Cipher.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0020DE98.
我当前的代码:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <math.h>
using namespace std;
int main()
{
//GLOBAL_VARS
string mainInput;
string aboutInput;
string encrInput;
int encrKey[2] = {5, 14}; //Temp Key
const int nValues = 26; //How many values within the array
string letterArray[nValues] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; //Array of letters
string capsArray[nValues] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; //Array of capital letters
//MAIN_MENU
while ((mainInput != "Exit") || (mainInput != "exit") || (mainInput != "4"))
{
cout << "\n---RSA Cipher [Main Menu]---\n\n"
<< "1: About\n"
<< "2: Encrypt\n"
<< "3: Decrypt\n"
<< "4: Exit\n\n";
cin >> mainInput;
//ABOUT_MENU
if ((mainInput == "about") || (mainInput == "About") || (mainInput == "1"))
{
cout << "\n---RSA Cipher [About]---\n\n"
<< "This applicaton was designed to encrypt or decrypt information using RSA encryption.\n\n"
<< "1: Back\n\n";
cin >> aboutInput;
}
else {
//ENCRYPT_MENU
int encrLength;
int encrNum;
string encrGet;
string encrOutput;
if ((mainInput == "Encrypt") || (mainInput == "encrypt") || (mainInput == "2"))
{
cout << "\n---RSA Cipher [Encrypt]---\n\n"
<< "Enter a string to encrypt.\n\n";
cin >> encrInput;
encrLength = encrInput.length(); //Sets the variable to equal the length of the users input so that both items being compared are signed.
int iLength = 0;
while (iLength < encrLength)
{
encrGet = encrInput[iLength]; //Grabs a value of the entered string in order
int iIndex = 0;
while (iIndex < nValues)
{
if ((encrGet == letterArray[iIndex]) || (encrGet == capsArray[iIndex]))
{
encrNum = pow(iIndex + 1, encrKey[0]); //Sets the variable to equal array index + 1 (the alphabet starts at 1 not 0) to the power of the first encrKey value
encrNum = encrNum % encrKey[1]; //Sets the variable to equal it'self mod the second encrKey value
encrOutput = encrOutput + letterArray[encrNum - 1]; //Adds the letters to the soon to be output -1, as we are now dealing with computer logic.
}
iIndex++;
}
iLength++;
}
cout << "Encrypted: " << encrOutput << endl;
}
}
}
//END-MAIN_MENU
}
可能不在您发布的代码中。如果你想帮助解决你的代码问题,你真的需要发布一个可以被“任何人”编译和运行的完整示例。 –
顺便说一句,'bad_alloc'意味着你的系统不能满足'new'的内存分配。要么因为你要求疯狂的内存量,要么永远分配新的内存。 –
'encrKey [1]'是14和''n''是第14个字母之间有一些联系。这可能会导致'letterArray [encrNum - 1]'的超出范围的访问。 –