1

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;
}
Salvankar
  • 91
  • 6
  • 2
    First of all use a *debugger* to catch the exception to locate where in your code it's thrown. And once you've done that then you can examine variables to see if they can give any hints about the problem. – Some programmer dude Apr 24 '21 at 14:29
  • 2
    As a hint, the only place where you (indirectly) does memory allocation is when you push back into the `result` vector. How many elements are you adding to the vector? Are you sure that the the outer `while` loop will ever end? – Some programmer dude Apr 24 '21 at 14:30
  • 1
    How can `flag` ever become `false` and stop the looping? – Galik Apr 24 '21 at 14:32

1 Answers1

2

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

ph3rin
  • 4,426
  • 1
  • 18
  • 42