Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

c++17

I am trying to solve Leetcode problem 746 which is a basic Dynamic programming problem. 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] updating code but what the problem is, I have no idea.

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        if(cost.size() < 3)
            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]);
    }
};
like image 427
Sma Avatar asked Nov 26 '25 18:11

Sma


1 Answers

The initial value of i is 1. It can increment by 4 in one iteration of the while under different conditions (if the first else if and the second if are true).

So in the second iteration of the while, the value of i can become 9.

So in the last else if, cost[i+2] is cost[11]. Since your dataset has only 10 elements (as mentioned in the comment), this results in an out-of-bounds access.

like image 186
P.W Avatar answered Nov 29 '25 13:11

P.W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!