mardi 2 avril 2019

Why does my program keep on giving me heap buffer overflow even though I am not going out of bounds on my array or overwriting any values

I am trying to solve Leetcode problem 746 which is a basic Dynamic programming porblem. Even though my logic is little complex, it should work perfectly fine. I have had 2 sleepless nights trying to find what the problem in my code is. Can someone point exactly where am I doing heap overflow and how to avoid it ?

Also, I forgot to add, the size of cost is always greater than 3.

I have already tried inserting comments into my solution. I have realized that the problem lies with the costing[1] updation code but what the problem is, I have no idea.

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        if(cost.size()==0)
            return 0;

        int costing[2];
        costing[0]=cost[0];
        costing[1]=cost[1];
        int i=1;
        while(i<cost.size()-2)
        {
                if(costing[0]+cost[i]>costing[0]+cost[i+1])
                {
                    costing[0]=costing[0]+cost[i+1];
                    i++;
                }

                else if (costing[0]+cost[i]<=costing[0]+cost[i+1])
                {
                    costing[0]=costing[0]+cost[i];
                    i+=2;
                }

                if(costing[1]+cost[i+1]>=costing[1]+cost[i+2])
                {
                    cout<<costing[1]+cost[i+1]<<"is greater than " <<costing[1]+cost[i+2]<<"\n";
                    costing[1]+=cost[i+2];
                    i+=2;
                }

                else if (costing[1]+cost[i+1]<costing[1]+cost[i+2])
                {
                                    cout<<costing[1]+cost[i+1]<<"is less than " <<costing[1]+cost[i+2]<<"\n";

                costing[1]+=cost[i+1];
                    i++;
                }
        }

        return min(costing[0],costing[1]);
    }
};

Aucun commentaire:

Enregistrer un commentaire