Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my code showing heap buffer overflow

This is the title of the Leetcode 2367. The number of arithmetic triples
Gives you an array of integers nums with a subscript starting at 0 and strictly increasing and a positive integer diff. A triplet(i, j, k)is an arithmetic triplet if all of the following conditions are met:
i < j < k ,
nums[j] - nums[i] == diff
nums[k] - nums[j] == diff

this is my code

class Solution {
public:
    int arithmeticTriplets(vector<int>& nums, int diff) {
        int ans = 0;

        for (int i = 0; i < nums.size() - 2; i++) {
            for (int j = i + 1; i < nums.size() - 1; j++) {
                if (nums[j] - nums[i] == diff) {
                    for (int k = j + 1; k < nums.size(); k++) {
                        if (nums[k] - nums[j] == diff) ans++;
                    }
                }
            }
        }

        return ans;
    }
};

But I couldn’t pass the assessment
show that
==22==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x503000000090 at pc 0x558615c49233 bp 0x7fffb82e42b0 sp 0x7fffb82e42a8

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your second level loop, you never test the value of j, and since i is not updated, it can continue looping until nums[j] results in an out of bounds memory access.

        for (int i = 0; i < nums.size() - 2; i++) {
            for (int j = i + 1; i < nums.size() - 1; j++) {
                if (nums[j] - nums[i] == diff) {
                    for (int k = j + 1; k < nums.size(); k++) {
                        if (nums[k] - nums[j] == diff) ans++;
                    }
                }
            }
        }

You probably wanted:

for (int j = i + 1; j < nums.size() - 1; j++)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading