previous | start | next

6. Correcting the Memory Leak

To avoid the memory leak, simply delete the dynamic array in the loop after each use.

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);

        delete [] nums;

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


previous | start | next