开发者

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

I'm trying to enc开发者_JAVA技巧rypt 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.


You're trying to modify a string constant. For obvious reasons (it's constant), this won't work. Instead, do this:

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


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";


Mike has answered this question well. You cannot modify constant string literals. Time of DOS has almost ended. Proper up-to-date production level C++ compiler should have issued a warning with appropriate flags. Just to add a little bit to the Mike's answer, here is a good explanation of constant string literals - http://msdn.microsoft.com/en-us/library/69ze775t(v=vs.80).aspx

Also, here is the better way to do it:

#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] ^= pKey[i % lenKey];
}

int main()
{
    char data[] = "any binary string here";
    const char key[] = "key";
    crypt (data, sizeof(data) - 1, key, sizeof (key) - 1);
    std::cout << data << std::endl;
}

Note post-increment operator, ^= and sizeof operators. For simple types compiler will do this micro-optimization for you, but developing a good habit is good. If you have a complex iterator, using post-increment can harm you on performance critical paths. Also, hardcoding size of strings is error-prone. Later you or someone else can change the string and forget to change its length. Not to mention that every time you have to go and count number of characters.

Happy coding!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜