Memory Leaks and Constructor questions

Hello there

I wrote a little dice rolling program using a Class. I was worried that there was a chance of a memory leak, and I'm not 100% sure of all the causes besides using 'new' operator and then not deleting the allocated space.

The part I was wondering about was the Constructor. Is it okay to set the parameters for 'time' and srand here? And is it causing a memory leak or is there a different problem with it?

The program compiles and runs well, but I just want to make sure that I didn't commit any no-no's.

Also, any other problems with the program besides what I asked about? I'm using 'Dev C++' by the way.

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
#include <cstdlib>
#include <iostream>
#include <time.h>

using namespace std;

const int high=6;
const int low=1;

class cDice{

          time_t seconds;
     public:
          cDice();
          ~cDice();
          int roll();
};

cDice::cDice(){

     time(&seconds);
     srand((unsigned int) seconds);
}

int cDice::roll(){

     return rand()%(high-low+1)+low;
}

cDice::~cDice(){}

int main(int argc, char *argv[]){

     int x;
     cDice dice;

     cout << "How many dice would you like to roll? : ";
     cin >> x;
     cout << endl;

     for(int i=0; i<x; i++){

          cout << "die " << i+1 << " : " << dice.roll() << endl;
     }

     system("PAUSE");
     return EXIT_SUCCESS;
}


Thanks
I'm not 100% sure of all the causes besides using 'new' operator and then not deleting the allocated space.

There isn't anything else that can cause a classical memory leak.

Is it okay to set the parameters for 'time' and srand here?

No. The PRNG should be seed once at the beginning of the program, not every time a dice is constructed.
This has nothing to do with memory leaks, though.

Also, any other problems [...] besides what I asked about? I'm using 'Dev C++' by the way.

Yeah, see http://www.cplusplus.com/forum/articles/36896/
Also, high and low have no real business being in global scope, they should be static members of the dice class.
Edit: and when the destructor isn't doing anything, you can omit it.
Last edited on
Thank you much!
Topic archived. No new replies allowed.