Question about Dynamic Memory Allocation

///Write a complete program that will randomly assign the values of 3 - 38 to an array of 70 integers and then print these values to the screen. A constructor must allocate memory dynamically and a destructor must free this memory at the end of the program. A separate member function will load the array. /////

Here is my code, every time i run it , the stop working window will pop up and i can't find whats wrong with it, can anyone help please.

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
  class MXX
{
	private:
        int *Base;
	public:
	MXX();
        ~MXX();
        void print();
};

MXX::MXX()
{
	int *Base = new int;
}

MXX::~MXX()
{
	delete [] Base;
}

void MXX::print()
{
	srand(time(NULL));
	int Size = 70;
        int *Base = new int [Size];

	
	for(int i=0; i<Size; i++)
	{
		Base[i] = 3+rand()%35;
		cout<<Base[i]<<" ";
	}
	delete [] Base;
}
int main()
{
	
	MXX M;
	M.print();


	return 0;
}
You are leaking memory, and deleting the same pointer twice which results in undefined behavior.

Only allocate memory in the constructor. Only delete memory in the destructor.
You're also using mismatched new and delete operators. Kind of. Except that you're using new twice and delete twice, once with an array and once without, so it's all a bit of a big mess, but you're shadowing a class variable on line 25... Bleurgh. What a mess.

Look at the instructions again.
A constructor must allocate memory dynamically and a destructor must free this memory

So just do that. No allocation anywhere else, no deallocation anywhere else. Just follow the instructions.
Last edited on
Topic archived. No new replies allowed.