test class with array dynamic memory

hello.
I'm testing the "classes" and I tried to insert an array in the following exercise, a variant of the example proposed by the tutorial.
The program is regularly compiled and starts executing, but at some point, it crashes.

Also, if I move the "m.printer ()" outside "while" loop, the program compiles, but when I run it, it gives me an error like: bad_alloc ().

thanks for any suggestions.
bye
p.s.- have not added comments because it is a very simple program.
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

#include <iostream>
using namespace std;

class test
  {
    private:

            int x;
            int y;

            int size;
            int* multi = new int[size]; 

    public:
            int counter = 0;
            void set_values (int, int);
            void multipler (int, int);
            void printer ();
    };

inline void test::set_values ( int a, int b )
  {
    x = a;
    y = b;

    size = counter;
    }


inline void test::multipler ( int c, int d)
  {
    multi[counter] = c * d;
    counter++;
    }



inline void test::printer ()
  {
    for ( int j=0; j<counter; j++)
      {
        cout << " result is: " << multi[j] << " counter : " << counter << endl;
        }
    }


int main()
{
  class test m;
  int a, b;

  while ( m.counter < 10 )
    {
        cout << " input a, b " << endl;

        cin >> a >> b;

        m.set_values (a,b);

        cout << " ### " << endl;

        m.multipler(a,b);

        m.printer();

      }

    //m.printer();

  return 0;
}
Your code has undefined behaviour.

1
2
            int size;
            int* multi = new int[size]; 

data member size is not initialized. So the second statement
int* multi = new int[size];
has undefined behaviour.
thanks vlad. you're right.

:)
Topic archived. No new replies allowed.