Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generateKey cpp function

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have two serious problems:

  1. 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.

  2. The second problem is that you return a pointer to local data.

    Once the function generateKey returns, 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading