[英]C++ Unhandled Exception: std::bad_alloc
我一直在花时间来学习有关加密的更多知识,以及一般而言的密码。 我开始在控制台应用程序上工作,以允许我加密或解密RSA类型密码。
到目前为止,除了我要加密的字符串中包含字符“ n”时,其他所有内容似乎都运行良好。 由于某些原因,只有字母“ n”会强制应用程序中止。 本身是否在其他字符串中是否为“ n”并不重要。 它只是不喜欢“ n”。
我仍然是编码方面的学生,这只是我在C ++中的第二个应用程序。
错误:
RSA Cipher.exe中0x7743C42D的未处理异常:Microsoft C ++异常:内存位置0x0020DE98的std :: bad_alloc。
我当前的代码:
#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
}
所以问题就像@molbdnilo提到的...
当encrNum%encrKey [1]为零时,会发生此问题,只要encrNum == encrKey [1]就会发生。 看起来您在基于零的索引和基于一的索引之间存在冲突。
幸运的是,当处理一个真正的密钥而不是一个临时的简单密钥时,不会发生这种冲突,因为我们将处理2048位或4096位密钥。 然而,有趣的是,当模返回0作为余数时,会出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.