简体   繁体   中英

Why am I getting AddressSanitizer: heap-buffer-overflow on address 0x602000000058 error on leetcode?

I have read few other answers and checked a blog on codeforces. All suggest that it must be some potential overflow. I have tested it for all the testcases from n = 1 to n = 45. I don't see that overflow.

class Solution {
public:
    int checkSteps(int n, vector<int>&cache){
       if(n <= 0)
         return cache[0];
       else if(n == 1){
           return cache[1];
       }
       else if(n == 2){
           return cache[2];
       }
       if(cache[n] > 0) return cache[n];
       cache[n] = checkSteps(n-1, cache) + checkSteps(n-2, cache);
        return cache[n];
    }

   int climbStairs(int n){
           vector<int> cache(n+1, 0);
           cache[0] = 0;
           cache[1] = 1;
           cache[2] = 2;
          int result = checkSteps(n, cache);
           return result;

   }

You can also use the Fib Number formula ( Golden Ratio ) for this problem, will get accepted:

struct Solution {
    static const inline int climbStairs(const int n) {
        double ways = 1 / pow(5, 0.5) * (pow((1 + pow(5, 0.5)) / 2, -~n) - pow((1 - pow(5, 0.5)) / 2, -~n));
        return (int) ways;
    }
};
  • -~n is simply ( n + 1 ), just a bit shorter

or based on your approach, we would just iterate:

struct Solution {
    static const inline int climbStairs(const int n) {
        int first = 1;
        int second = 0;
        int ways = 0;

        for (int iter = 0; iter < n; iter++) {
            ways = first + second;
            second = first;
            first = ways;
        }

        return ways;
    }
};

References

  • For additional details, you can see the Discussion Board . There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time / space complexity analysis 1 , 2 in there.

If you are preparing for interviews :

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