Random string generation

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

char *charStr;
int stringLength;

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

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

    charStr[stringLength] = 0;
}

int main()
{
    while(true)
    {
        genRandom();
        cout < charStr;
    }
    return 0;

}

The problem occurs during compilation. It will compile just fine, but nothing is displayed, and then the program will stop working. So my question is: what's wrong with this code?

+5
source share
3 answers

A few problems with the code:

cout < charStr;

it should be:

cout << charStr;

If you compile the g ++ -Wall argument (all warnings), this error becomes apparent.

, stringLength! , - . stringLength - 0, . undefined , , (, , , ).

:

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

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

int stringLength = sizeof(alphanum) - 1;

char genRandom()
{
    return alphanum[rand() % stringLength];
}

int main()
{
    while(true)
    {
        cout << genRandom();
    }
    return 0;

}

- , , . , , char *, , . , ++ ++, - .

+8

stringLength 0, . - charStr, 0 NULL ( ). , cout << charStr, < (, ).

, ... , nosrils.

+2

DashRantic : " stringLength - 0, ".

C/++ , GLOBAL- 0 (. Uninitialized Structures C). (/ ), . , , , stringLength 0.

Therefore, your code should not output, because charStr [0] is null at the end of the for loop (which, again, according to the standard, is not guaranteed to be fulfilled, since the condition is checked before the first iteration of the loop).

Unfortunately, due to the same rules, charStr is guaranteed to be initialized to 0, so your null character is written to address 0 (where charStr points to). Depending on your runtime, this may or may not cause a problem.

+1
source

All Articles