-2

Hello!

Currently creating a program in C++ which purpose is to encrypt a phrase with a Caesar Cipher and cannot figure out what the issue is here after several tries of debugging in Microsoft Visual Studio 2017 Community.

Problem

reference operator[](const size_type _Off)
    {   // subscript mutable sequence
    _IDL_VERIFY(_Off <= this->_Mysize(), "string subscript out of range"); //(Here, a breakpoint is triggered)
    return (this->_Myptr()[_Off]);
    }

No errors or warnings are shown in the error list but in runtime my program "jumps" into a library called "xstring" and stops inside this function(see code).

Debug output

    Debug Assertion Failed!

Program: C:\Windows\system32\MSVCP140D.dll
File: c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xstring
Line: 2944

Expression: string subscript out of range

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

Encryption function

int encrypt(string plainText, string cipherText, int length, int key)
{
    int charLength = (int)plainText.length();
    if (key < 0)
    {
        return -1;
    }

    for (int i = 0; i < charLength; i++)
    {

        if (isalpha(plainText[i]))
        {
            plainText[i] = tolower(plainText[i]);
            cipherText[i] = plainText[i];

            for (int j = 0; j < key; j++)
            {

                if (cipherText[i] == 'z')
                {
                    cipherText[i] = 'a';
                }

                cipherText[i]++;
            }
        }
        
    }

    return charLength;
}
Community
  • 1
  • 1

1 Answers1

0

You never check the size of cipherText before writing to it. Are you sure it has the proper size? Given the error you have and the little information we've got, that would be the cause.

Try adding

cipherText.resize(charLength);

right after int charLength = (int)plainText.length();

AlexG
  • 1,091
  • 7
  • 15