Search code examples
c++windowsg++constantsstring-constant

Error when running g++ app. (encryption of string)


I'm trying to encrypt and decrypt files with C++, using this code:

#include <iostream>

void crypt(char* pData, unsigned int lenData, const char* pKey, unsigned int lenKey)
{
    for (unsigned int i = 0; i < lenData; i++)
        pData[i] = pData[i] ^ pKey[i % lenKey];
}

int main()
{
    char* data = (char*)"any binary string here";
    crypt(data, 22, "key", 3);
    std::cout << data;
}

I'm compiling with g++ (tdm-1) 4.5.1 (MinGW) on Windows 6.1 (Seven), it compiles with no errors or warnings. When I try to run, it shows a window with "app.exe stoped working. The Windows can check online if there has some solution to the problem." (some thing like that, my Windows isn't in English). I don't have any idea about what is wrong.


Solution

  • This line is wrong:

    char* data = (char*)"any binary string here";
    

    First, you should not use a cast. Next, a string literal is a constant. So it should be:

    const char* data = "any binary string here";
    

    But you're wanting to overwrite it. So you need a string that isn't a constant. Like this:

    char data[] = "any binary string here";