简体   繁体   中英

Runtime Error in a recursive function : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

I am using a recursive function ans1 to find a suitable string , but I'm having runtime error:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc**
void ans1(vector<int>a,int x , int val,string s,int req)
{
    if(x<0||val>req)
    return ;

    if(val==req)
    {
       cout<<s<<endl;
        return ;
    }
    char c='a'+x;
    
    ans1(a,x-1,val,s,req);
    s.push_back(c);
    ans1(a,x,val+a[x],s,req);

    
}

What is the problem?

You are passing a by value! This means that you are creating copy of std::vector<int> for each recursion step. If a is big the you allocating lots of memory. Change argument to const vector<int>& a and problem should be fixed.

In case of s problem is more complicated since you are modify it. You could use string &s , but you have to remember to restore old value when coming back from recursion, to avoid side effects.

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