简体   繁体   中英

heap-buffer-overflow on address

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]

Output: 2

My approach is read each element and then multiply that index by -1. Whichever array index remains positive is the one that's missing (I have to handle zero separately)

My code causes a heap overflow on line where I try to multiply the element by -1

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        bool zeroFound = false;
        for(auto i = nums.begin(); i < nums.end(); i++) {
            if(*i == 0) {
                zeroFound = true;
            } else {
                int value = *i;
                printf("Inner %d %d\n", value, nums[value -1]);
                //nums[value - 1] = value * (-1);
            }   
        }
        if(!zeroFound) {
            return 0;
        } else {
            int count = 1;
            for(auto i = nums.begin(); i < nums.end(); i++, count++) {
                if(*i > 0) {
                    return count;
                }
            }
        }
        return -1;
    }
};

Learn to use a debugger.

Your problem is that after the first run through the loop, the input is [3, 0, -3] . When you process the final element, you try and access element -4, which is never going to end well.

Even if you use the absolute value of the element, your first run will have overwritten the last element - so you can no longer tell whether the input was [3, 0, 1] or [3, 0, 2] .

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