Trying to make a dynamic array, having memory issues that I am not able to identify.

I am trying to work with dynamic arrays and somewhere in my code I have a segmentation fault that I cannot seem to find. I am not great at c++ classes yet. I have stared at this for hours and would appreciate any help that I can get. Thank you.

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
  #include <iostream>
#include <stdlib.h>
#include <unistd.h>

using namespace std;

class Doubling {

private:                            //private variables
    int *arr;
    int size;
    int used;

public:
    Doubling() {    //initializer

        size = 2;
        used = 0;
        arr = new int[size];          //creating array, fill with zeros
        for (int i = 0; i < size; i++) {
            arr[i] = 0;
        }

    }

    Doubling(int init[], int size) {
        int *newer;                         //constructor
        int i, j;
        size = 2;
        used = 0;

        while (used >= size) {                 //if used is equal to size
            newer = new int[size * 2];            //make a double sized array
            for (i = 0; i < used; i++) {
                newer[i] = arr[i];              //swap elements over to new array
            }
            for (j = used; j < size; j++) {             //fill the rest with zeros
                newer[j] = 0;
            }
            size = size * 2;                    //reset size

            delete arr;                         //delete old array
            arr = newer;                        // new array is now the array
        }
    }

    void add(int toAdd) {
        int *newer;
        int m, n, y;                        //variables for add function
        newer = new int[size * 2]{0};          //double size array
        if ((used + toAdd) >= size) {       // if used and to add is greater than size


            for (m = 0; m < used; m++) {
                newer[m] = arr[m];          //swap over elements
            }
            for (y=used; y < toAdd; y++) {      //add whatever amount of random numbers
                arr[y] = rand() % 10;
                used++;                         //and increase used
                toAdd--;                        //subtract toAdd
            }
            for (n = used; n < size; n++) {        //fill the rest with zeros
                newer[n] = 0;
            }


        }
        size = size * 2;                        // the new size is now the size
//        delete arr;                             //delete old array
        arr = newer;                            //new array is now the array
    }

    void print() {
        int k, l=0;
        for (k=0, k < used; k++;) {             //for all used elements
            cout << "The array is " << getSize() << " elements long and contains the following numbers:" << endl;
            if (l == 10){                           //and a new line every ten elements
                cout << endl;
                l = 0;
            }
            else {
                cout << arr[k] << ' ';              //spit out used elements
                l++;
            }
        }

    }

    int getSize() {                     //a size-getter
        return size;
    }
};


int main() {
    Doubling d;
    int var = 0;
    cout << "please enter the number of elements to add: ";
    cin >> var;
    d.add(var);
    cout << "after add" << endl;
    d.print();
    cout << "after print";
    sleep(10);

    return 0;
}
I’ve added some comments to your code:
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
#include <stdlib.h> // remove this
#include <unistd.h> // remove this

using namespace std; // <-- remove this: it's for experts only.

class Doubling {
private:  //private variables <-- remove all pointless comments like this
    int *arr;
    int size;
    int used;

public:
    Doubling() { //initializer <-- it's called constructor. Just remove this comment.
        size = 2;
        used = 0;
        arr = new int[size];          //creating array, fill with zeros
        for (int i = 0; i < size; i++) {
            arr[i] = 0;
        }
    }

    // Describe this overloaded constructor. What is it supposed to do?
    // You neglect "init[]".
    Doubling(int init[], int size) {
        int *newer; //constructor <-- ???
        int i, j;
        size = 2;
        used = 0;
        while (used >= size) {                 //if used is equal to size
            newer = new int[size * 2];            //make a double sized array
            for (i = 0; i < used; i++) {
                newer[i] = arr[i];              //swap elements over to new array
            }
            for (j = used; j < size; j++) {             //fill the rest with zeros
                newer[j] = 0;
            }
            size = size * 2;                    //reset size
            delete arr;                         //delete old array
            arr = newer;                        // new array is now the array
        }
    }

    void add(int toAdd) {
        int *newer;
        int m, n, y;                        //variables for add function
        newer = new int[size * 2]{0};          //double size array

        if ((used + toAdd) >= size) {       // if used and to add is greater than size
// ----------------------------------------------------------------------------
//  -------->  Here you copy everything into arr...
// ----------------------------------------------------------------------------
            for (m = 0; m < used; m++) {
                newer[m] = arr[m];          //swap over elements
            }
            for (y=used; y < toAdd; y++) {      //add whatever amount of random numbers
                arr[y] = rand() % 10;
                used++;                         //and increase used
                toAdd--;                        //subtract toAdd <-- Why?
            }
            for (n = used; n < size; n++) {        //fill the rest with zeros
                newer[n] = 0;
            }


        }
        size = size * 2;                        // the new size is now the size
        //        delete arr;                             //delete old array
// ----------------------------------------------------------------------------
// ---> ...and here you tell arr to point to a new memory area.
// ----------------------------------------------------------------------------
        arr = newer;                            //new array is now the array
    }

    void print() {
        int k, l=0;
        // Read compiler warnings:
        // a) there's a comme instead of a semicolon
        // b) there's an extra semicolon
        for (k=0, k < used; k++;) {             //for all used elements
            // Move the following 'cout' outside the loop.
            cout << "The array is " << getSize() << " elements long and contains the following numbers:" << endl;
            if (l == 10){                           //and a new line every ten elements
                cout << endl;
                l = 0;
            }
            else {
                cout << arr[k] << ' ';              //spit out used elements
                l++;
            }
        }
    }

    int getSize() {                     //a size-getter
        return size;
    }
};


int main() {
    Doubling d;
    int var = 0;
    cout << "please enter the number of elements to add: ";
    cin >> var;
    d.add(var);
    cout << "after add" << endl;
    d.print();
    cout << "after print";
    sleep(10);

    return 0;
}


Anyway:
Bjarne Stroustrup, The C++ Programming Language - Fourth Edition, Chapter 4.6 Advice
Don’t reinvent the wheel; use libraries;


A different basic example of ‘dynamic array’ based on your code could be:
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>
#include <limits>

class Doubling {

private:
    int size;   // max capacity before doubling
    int used;   // elements stored so far
    int* arr;

public:
    Doubling() : size { 2 }, used { 0 }, arr { new int[size]{} } {}

    Doubling(int size_arg) 
        : size { size_arg }, used { 0 }, arr { new int[size]{} }
        {}

    void add(int to_be_added)
    {
        if(used < size) {
            arr[used++] = to_be_added;
            return;
        }

        int newsize = size * 2;
        int* new_arr = new int[newsize] {};
        for(int i{}; i<size; ++i) { new_arr[i] = arr[i]; }
        new_arr[used++] = to_be_added;
        delete[] arr;
        arr = new_arr;
        size = newsize;
    }

    void print() const
    {
        std::cout << "The array is " << used << " elements long and contains "
                     "the following numbers:\n";
        for (int k=0, l=0; k < used; k++) {
            //and a new line every ten elements
            if (l == 10) { std::cout << '\n';           l = 0; }
            else         { std::cout << arr[k] << ' ';  l++;   }
        }

    }

    int getSize() const { return size; }
};

void waitForEnter();

int main() {
    Doubling d;
    std::cout << "please enter the number of elements to add: ";
    int var = 0;
    std::cin >> var;
    for(int i{}; i<var; ++i) {
        std::cout << "Next number to insert? ";
        int num;
        std::cin >> num;
        d.add(num);
    }
    std::cout << '\n';
    d.print();
    waitForEnter();
    return 0;
}

void waitForEnter()
{
    std::cin.ignore(1000, '\n');
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Output:
please enter the number of elements to add: 5
Next number to insert? 6
Next number to insert? 7
Next number to insert? 8
Next number to insert? 9
Next number to insert? 10

The array is 5 elements long and contains the following numbers
6 7 8 9 10
Press ENTER to continue...

Topic archived. No new replies allowed.