Hello i have a problem with one of my functions generateKey() that returns char*.
Its generate the key normal but when i print it i can see something weird.
char* aesStartup::generateKey()
{
const char alphanum[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char newKey[32];
srand(time(0));
for (int i = 0; i < 32; i++)
newKey[i] = alphanum[rand() % 62];
cout << newKey;
return newKey;
}
output: u6gWj8dBHxJhEztsHXfE5V3HSvZ2zVNb╠╠╠╠╠╠╠╠0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
can someone help me?
>Solution :
You have two serious problems:
-
First of all you seem to have forgotten that strings in C++ are really called null-terminated strings.
For an array of characters to be a "string" it needs to be terminated with the
'\0'character. Which also means a 32-character string needs to have 33 elements. -
The second problem is that you return a pointer to local data.
Once the function
generateKeyreturns, the life-time of all local variables ends, and pointer to them will become invalid.
You can solve both problems very easily: Stop using character arrays for strings, and start using the C++ standard std::string class for all your strings.
On another note, you should only call srand once in your program. And C++ have much better functions and classes for generating random numbers than the C compatibility functions srand and rand.