Memory leak in code

I wrote this competitive code for this problem

my code:

//Code begins
#include <iostream>
#include<list>
using namespace std;

struct num{
    
    int n,d;
};
int main()
{
    int n,k;
    cin>>n>>k;
    if(k==1){
        cout<<"0/1";
    }
    if(n==0||n==1 && k==2){
        cout<<"1/2";
    }
    if(k<=4){
        cout<<"1/"<<n-k+2;
    }
    list<num> v;
    num temp;
    temp.n=0;
    temp.d=1;
    v.push_back(temp);
    
    for(int i = n ; i >= 2 ; i--){
        temp.n=1;
        temp.d=i;
        v.push_back(temp);
    }
    
    list<num> :: iterator it,it1;
    num temp2,temp3;
    for(it=v.begin();it!=v.end();++it){
        temp=*it;
        it1 = next(it,1);
        temp2=*it1;
        temp3.d= temp.d+temp2.d;
        
        if(temp3.d <= n){
            temp3.n = temp.n + temp2.n;
            v.insert(it1,temp3);
            
        }
        //cout<<temp.n<<"/"<<temp.d<<eIdl;
        
    }
    for(it=v.begin();it!=v.end();++it){
        temp=*it;
        if(k==1){
            cout<<temp.n<<"/"<<temp.d<<endl;
        }
        k--;
    }
    return 0;
}

I am having trouble in it as there is somewhere memory leak in it and I am unable to find it supposedly it is using over 250MB while running can anyone please help me and show me how to solve this problem

When you are reaching the last element of the list supposedly “1/2” in any case…you are still accessing its next iterator ( it1 ) which is basically v.end()…and you are trying to access value at that…which is going to be random (possibly <=0) and your code goes on and on because the temp3.d part will always be less than ‘n’ if you keep adding 0 or negative elements.

Just adding a simple line if( it1==v.end() ) break; …should do the trick for you.

UPDATE : You’re gonna get a WA with the approach you used.Even after rectifying the Runtime error for case n=8 k=9 it gives 2/5 as the answer while the actual answer will be 3/8.