为什么我会出现记忆错误

Why am i getting memory errors?

本文关键字:记忆 错误 为什么      更新时间:2023-10-16

当我运行这个c++程序并执行它的函数时,我得到了这个内存错误

TESTER 12345.exe中0x769DC41F处未处理的异常:内存位置0x0042F558处的Microsoft C++异常:std::invalid_argument。

我在Visual studio 2013上运行这个。

#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cmath>
using namespace std;
string encrypt(string, int);
string decrypt(string source, int key);
int main(int argc, char *argv[])
{
    string Source;
    string userInput;
    string keyString;
    int Key;
    int locationSpace = 0;
    int locationOfFirstKeyIndex = 0;
    int choice;
    /*locationSpace = userInput.find(" ");
    keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
    Source = userInput.substr(locationSpace + 1);
    Key = stoi(keyString);*/
    cout << "To encode a message type 1, to decode a message type 2: ";
    cin >> choice;
    if (choice == 1)
    {
        cin.ignore();
        cout << "Enter a message to decode: ";
        getline(cin, Source);
        locationSpace = userInput.find(" ");
        keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
        Key = stoi(keyString);
        Source = userInput.substr(locationSpace + 1);
        encrypt(Source, Key);
        cout << "Encrypted: " << encrypt(Source, Key) << endl;
    }
    else if (choice == 2)
    {
        cin.ignore();
        cout << "Enter the message To decode: ";
        getline(cin, userInput);
        locationSpace = userInput.find(" ");
        keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
        Key = stoi(keyString);
        Source = userInput.substr(locationSpace + 1);

        decrypt(Source, Key);
        cout << "Decrypted: " << decrypt(Source, Key) << endl;
    }
    else
    {
        cout << "Invalid Input";
    }
    system("pause");
}
string encrypt(string source, int key)
{
    string Crypted = source;
    for (int Current = 0; Current < source.length(); Current++)
        Crypted[Current] = ((Crypted[Current] + key) - 32) % 95 + 32;
    return Crypted;
}
string decrypt(string source, int key)
{
    string Crypted = source;
    for (int Current = 0; Current < source.length(); Current++)
        Crypted[Current] = ((Crypted[Current] - key) - 32 + 3 * 95) % 95 + 32;
    return Crypted;
}

请参阅以下链接了解这一点:

http://en.cppreference.com/w/cpp/string/basic_string/stol

当无法执行转换时,stoi方法抛出*std::invalid_argument*异常。您可能需要在将其传递到stoi()之前进行打印,并验证字符串是否有效。

std::cout<<keyString<<std::endl;

我假设错误是在取消注释代码时引起的。让我们运行该错误(您应该是使用调试器执行此操作的人):

keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace); 
//userInput is a blank string, lOFKI == 0 and so does locationSpace
stoi(keyString); //keyString is invalid, empty string

在解析之前,您应该尝试获取用户输入…