简体   繁体   中英

Handling memory limitation correctly?

One of my class variables is a 2D array. The size depends on the user input. The user may input size which may exceed his hardware limit. So I want to handle this properly. Is the following code correct?

        int counter;
        try
        {
            int size = 20000;//this is actually from user input
            array = new double*[size];
            for(counter = 0; counter < size; counter++)
                array[counter] = new double[size];
        }
        catch(std::bad_alloc)
        {
            try
            {
                for(int i = 0; i < counter; i++)
                    delete[] array([i]);

                delete[] array;
                array = NULL;

                //display limitation message
                size = 2;
                array = new double*[size];
                for(int i = 0; i < size; i++)
                    array[i] = new double[size];
            }
            //catch again & exit application
        }

Your best bet is:

std::vector<std::vector<double>>  array(size, std::vector<double>(size));

But if you must do it manually then:

void init_array(int size)
{
    int counter;
    try
    {
        array = new double*[size];

        // Don't shadow counter here.
        for(counter = 0; counter < size; counter++)
        {
            array[counter] = new double[size];
        }
    }
    catch(std::bad_alloc)
    {
        // delete in reverse order to mimic other containers.
        for(--counter; counter >= 0;--counter)
        {
            delete[] array[counter];
        }

        delete[] array;

        // retry the call with a smaller size.
        // A loop would also work. Depending on context.
        // Don't nest another try{} catch block. because your code will
        // just get convoluted.
        init_array(size/2);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM