Home > front end >  generateKey cpp function
generateKey cpp function

Time:01-10

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?

CodePudding user response:

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.

CodePudding user response:

You are missing the \0 (NUL) character at the end of your chars. At newKey[31] needs to be \0. Otherwise you print more than you wish.

In your example the \0 is within alphanum at the end, position 63. So the program reads all memory until it "sees" the \0.

Either you switch to use std::string which handles this for you, or you need to make sure that all your char arrays are null-terminated, by:

  • making them one larger than your expected output: char newKey[33];

AND

  • insert '\0' at the end: newKey[32] = '\0';.
  •  Tags:  
  • Related