是什么在下面的代码中导致缓冲区溢出错误

时间:2019-12-08 07:13:49

标签: vector heap-corruption address-sanitizer

无法在下面的代码中找出导致缓冲区溢出的原因。我认为这与向量有关,但我在防止越界访问。还有其他可能导致溢出的东西吗?

class Solution {
public:
    bool canPartition(vector<int>& nums) {
        int sum = 0;
        bool canPartition = true;
        vector<vector<int>> dp(nums.size(), vector<int>(sum / 2 + 1, -1));
        sum = accumulate(nums.begin(),nums.end(),0);
        if (sum % 2 != 0)
        {
            canPartition = false;
        }
        if (true == canPartition)
        {
            canPartition = canPartitionRecursive(nums, 0, sum/2, dp);
        }
        return canPartition;
    }
    bool canPartitionRecursive(vector<int>& nums, int index, int sum, 
                               vector<vector<int>>& dp)
    {
        if (sum == 0)
        {
            return true;
        }
        if (index >= nums.size() || sum < 0)
        {
            return false;
        }
        if (dp[index][sum] != -1)
        {
            if (true == canPartitionRecursive(nums, index+1, sum - nums[index],dp))
            {
                dp[index][sum] = 1;
                return true;
            }
            dp[index][sum] = canPartitionRecursive(nums, index + 1, sum, dp);
        }
        return dp[index][sum] = 1? true:false;
    }
};

1 个答案:

答案 0 :(得分:0)

这看起来像是换位错误(所有子向量的大小均为1):

int sum = 0;
vector<vector<int>> dp(nums.size(), vector<int>(sum / 2 + 1, -1));
sum = accumulate(nums.begin(),nums.end(),0);

也许sum的计算应该在dp初始化之前移动?