hey guys :) could you tell me why my bunny name generator crashes sometimes?

every know and again it crashes, not allways but every know and again, i checked the numbers and they dont go off the end of the array so i cant think what it may be...unless a junk number gets in...hrmmm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include<string>
#include<ctime>
#include<cstdlib>

using namespace std;
int getrand ();


class bunny{
public:
void setname (string x)
{
    name = x;
}
string getname()
{
    return name;
}
private:
string name;
};


string namelist ();

main()
{
bunny bun1;
bun1.setname (namelist());
cout << bun1.getname()<<endl;
}


int getrand ()
{

 srand(time(0));
return 1+(rand()%6);

}

string namelist ()
{
string namearray [15] = {"frufru ","baxter ","voldermort ","falafal ","fluffles "," flopsy "," panhandle ",
" bruchetta "," cottonflop "," pixie ","bouviay","lightening","cellotape","bonapart","jackson"};

string none = namearray [getrand()];
string ntwo =namearray [getrand()*2];
string nthree=namearray [getrand()*3];
string fullname=none+ntwo+nthree;



return fullname;
}
return 1+(rand()%6);
 
this generates random numbers in range [1,6]

getrand()*3 will be in range [3..18] which has 15, 18 that namearray (length 15) can't access

and srand(time(0)); call it once in main(), not in getrand()

try
string none = namearray [getrand() % 15];
string ntwo =namearray [getrand()*2 % 15];
string nthree=namearray [getrand()*3 % 15];
Line 50, the maximum value returned from "getrand()" is 6 and if you multiply that by 3 you get 18 which is outside the bounds of your array.
Last edited on
oh yeah...i thought that because of the plus one i would keep it above zero but 6 still is 18...thanks guys
Topic archived. No new replies allowed.