Thread: Issue with xoring C++ string

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    918

    Issue with xoring C++ string

    I am trying to use a C++ string as the key for xoring another string.
    The program crashes with (0xC0000005) Access violation.
    Though it works if the key is declared as char key[260].

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string buf  = "Value with the position of a character within";
        string key  = "Ak!$s**s1z*z*z*z*abjkvyuildoin*ek-+qsdfghjjop";
        string out;
        int arrSize = buf.length();
    
        for(int i = 0; i < arrSize; i++)
        {
            out[i] = buf[i] ^ key[i];
        }
    
        cout << "String size:    " << arrSize << endl;
        cout << "String encrypt: " << buf << "\n\n";
    
        for(int i = 0; i < arrSize; i++)
        {
            buf[i] = out[i] ^ key[i];
        }
    
        cout << "String decrypt: " << buf << endl;
        cout << "Key: " << key << endl;
    
        return 0;
    }
    Windows 10 with Visual Studio 2019 and MingW.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,289
    1. Your out has no size to start with.

    2. If you xor any character with itself, you end up with \0 (aka - the end of the string).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    918
    Thank you, that was it.
    Windows 10 with Visual Studio 2019 and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Xoring text with binary file
    By Ducky in forum C++ Programming
    Replies: 2
    Last Post: 10-06-2017, 06:58 AM
  2. Replies: 2
    Last Post: 08-06-2012, 08:59 AM
  3. String issue
    By cszym001 in forum C++ Programming
    Replies: 2
    Last Post: 07-15-2008, 01:28 PM
  4. fast XORing chars
    By zxcv in forum C Programming
    Replies: 9
    Last Post: 05-30-2008, 02:15 AM
  5. xoring
    By Sekti in forum C++ Programming
    Replies: 3
    Last Post: 06-20-2002, 02:35 PM

Tags for this Thread