0

I am trying to use a function to generate a char[] :

char* randString(){
    const int len = 5;
    char s[len] = {0};

    static const char alphanum[] =
        "0123456789"
        "!@#$%^&*"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    int stringLength = sizeof(alphanum) - 1;
    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % stringLength];
    }

    return s;
}

the result is random and expected at return s

+       s   0x002df990 "XnQWp...    char[5]

however, when i look at the value here:

char* rand = randString();

it contains strange values:

+       rand    0x002df990 "XnQWpÌÌÌÌÌÌÌÌÌÌÌ\x5"    char *

did I do something wrong in the return?

Epicblood
  • 1,167
  • 2
  • 10
  • 29

1 Answers1

2

You're declaring char s[] as a local variable. Local variables are destroyed when the function returns so returning a pointer to that variable returns a pointer pointing to junk data.

Fix this by allocating s dynamically:

char* s = new char[len];

Or you could pass a char* as a parameter and write your character to that array.

Just remember to add the terminating null character before returning.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157