I am trying to make a simple program for encrypting a char* with the XOR operator.
The code compiles and links perfectly, but I get an Access violation runtime error:
Unhandled exception at 0x1000435C (msvcr120d.dll) in encrypt.exe: 0xC0000005: Access violation reading location 0x0000794D.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <fstream>
usingnamespace std;
int main(int argc, char** argv)
{
if (argc < 2)
{
cout << "Error: First command line argument must be the output filename." << endl;
return -1;
}
char* text = newchar;
char key[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
char* encrypted = newchar;
printf("Enter the text to be encrypted: \n");
int x = 0;
scanf("%s", &text);
for (int i = 0; i < strlen(text); i++) // This line causes the error
{
encrypted[i] = text[i] ^ key[x];
if (x++>7) // Key is and 8 element array, so we need another counter to prevent array index out of bounds exception
{
x = 0;
}
}
FILE* file = fopen(argv[1], "w");
fprintf(file, "%s", encrypted); //write to file
return 0;
}
Line 17 allocates a single character.
Line 19 allocates a single character.
That means the only valid C-style string you can store is an empty one.
NOTE: I am using scanf and the other functions from the C library because I am inputting a C-style string.
No. You're using C-style input and output because you're using C-style input and output. It doesn't have anything at all to do with the specifics of the string representation.