previous | start | next

5. Memory Leak Example

If we modify the previous example to add a loop to repeat the 3 steps, we create garbage each time the nums pointer is assigned a new dynamic array.

int main()
{
    int sz;
    bool more = true;
    string ans;
    printDirections();
    
    while( more ) {
        cout << "How many integers to generate and sort? ";
        cin >> sz;
        int *nums = new int[sz];

        init(nums, sz);
        sort(nums, sz);
        print(nums, sz);

        cout << "\nAgain? [y/n] ";
        cin >> ans;
        if (ans == "n") {
            more = false;
        }
    }
    return 0;
}


previous | start | next