EDIT: The problem was not undefined behaviour, but rather "mis-use" of char-arrays
I haven't worked a lot with pointers and dynamic memory allocation, so I decided I'd try to make a really simple encrypter using these methods. (this encrypter isn't supposed to be great, it uses Caesars method, only +1 instead of 3, and uses symbols in between the letters to make it harder to decrypt, not here for criticism on the algorithm)
The problem I'm facing I believe is undefined behaviour, but I don't really see how this happens. Say I want "Hello" to be encrypted, it only prints 'I', which comes after 'H' in the alphabet, but it stops there and the program becomes unresponsive, so I suppose the problem lies in the else
part of the for loop. The compiler also warns me about heap corruption, but after looking through this page I think I'm freeing the memory correctly.
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
char * enc(string);
int main()
{
string foo = "Hello";
char * bar = enc(foo);
cout << *bar;
delete[] bar;
cin.get();
return 0;
}
char * enc(string str)
{
char * encrypted = new char[int(str.size())];
srand(unsigned int(time(NULL)));
// Disguise symbols for obscurifying text
char * disg = new char[37]
{
//37 symbols, unrelevant and takes a lot of space.
};
for (int i = 0; i < str.size(); i++)
{
encrypted[i] = int(str[i]) + 1;
if (i == str.size())
break;
else
encrypted[i + 1] = disg[rand() % 37];
}
delete[] disg;
return encrypted;
}
As a sidenote, I do realize that vectors might be better for this purpose, but I haven't gotten into that just yet, this is for practicing memory management.