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?

12
  • 5
    It's because you're returning a local pointer. Commented Feb 8, 2015 at 7:36
  • @ApproachingDarknessFish what do you mean? @Mat how is char s[len] = {0} out of bounds? I thought that was how you are supposed to init things Commented Feb 8, 2015 at 7:39
  • possible duplicate of Can a local variable's memory be accessed outside its scope? Commented Feb 8, 2015 at 7:39
  • 3
    As a side note, this would be more accurately tagged C than C++. Commented Feb 8, 2015 at 8:11
  • 1
    @Epicblood yes, pass a buffer and its length (a size_t ideally) as input params and let the function sort it out, including setting a terminating null (which you didn't forget, right ?). Commented Feb 8, 2015 at 8:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

and remember to delete[] it in the end, don't forget

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.