A
Andrei Zavidei
I wanted to create a string with 50 million chars (small letters from
a to z), but the program crashed...
//the function returns a string of length len
// with chars from a to z (small letters).
const len = 50000000;
void randomString(string &s)
{
srand((unsigned)std::time(0));
char cr [len+1];
for( int i = 0 ; i < len ; ++i )
{
int iNumber;
iNumber = rand() % 26 + 97;
cr = iNumber;
}
cr [len] ='\0';
s.assign(cr);
}
The above crashed when the length, len = 50000000 (50 million). How
come? Since I was trying to test something (something else this time,
as I have nothing else to do), an hour earlier I was doing the same
thing in java without any problem.
//returns a String of length len with lowercase letters from a to z
static String randomString(int len)
{
char[] cr = new char[len];
Random rd = new Random();
for (int i = 0; i < len; i++){
int num = rd.nextInt(26) + 97;
cr = (char) num;
}
return new String(cr);
}
They both look the same ... why the c++ version crashes?
Funny.
You say that "char[] cr = new char[len];" is the same as "char cr [len
+1];" ...
Please refresh your memories about heap and stack differencies. That
will guide you in the right direction.
Regards,
Andrei