Salvankar
Salvankar

Reputation: 101

What is the reason for std::bad_alloc in this function?

I have written below C++ function which loops through an integer vector. With each pass it subtracts smallest number from all its numbers. It is supposed to return the number of non zero elements at each pass(this is stored in the vector result and is returned). However I am getting "std::bad_alloc" evertime I try to run. The error is gone when remove the line "flag=true". I will need it to work so that the while loop breaks. Help me fix this.

vector<int> cutTheSticks(vector<int> arr) {
    int flag=true, min, count;
    vector<int> result;
    
    while(flag)
    {
        min = arr[0];
        flag = false;
        count = 0;
        for(int i=1; i<arr.size(); i++)
        {
            if(arr[i]<min) 
            {
                min=arr[i];
            }
        }
        for(int i=0; i<arr.size(); i++)
        {
            if(arr[i]!=0)
            {                
                count++;
                flag = true;
            }
            arr[i] = arr[i]-min;
        }
        result.push_back(count);
    }
    return result;
}

Upvotes: 1

Views: 1448

Answers (1)

ph3rin
ph3rin

Reputation: 4871

Consider the input [0, 1].

The minimum is 0, so you subtract 0 from every element (does nothing). Since the second element is 1 ( not 0 ) you set flag = true.

Nothing has changed in this loop except you have pushed back to the result vector. So the loop will repeat until vector runs out of memory (or exceeds its max_size).

Upvotes: 2

Related Questions