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

Error while finding the running sum of an array in C++ using vectors

Why am i getting this error, while finding the running sum of an array in c++?

Line 1034: Char 34: runtime error: addition of unsigned offset to 0x6020000000b0 overflowed to 0x6020000000ac (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34".

the code is:

    class Solution {
    public:
        vector<int> runningSum(vector<int>& nums) {
          vector<int> temp(nums.size());
            nums[0]=temp[0];
            for(int i=0;i<nums.size();i++){
                temp[i]=temp[i-1]+nums[i];
            }
              return temp;
        }
    };

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 :

nums[0]=temp[0] is incorrect, since temp[0] is 0 currently. It should be the other way around.

Also, the lower bound for the for loop should be i=1.

class Solution {
public:
    vector<int> runningSum(vector<int>& nums) {
      vector<int> temp(nums.size());
        temp[0] = nums[0];
        for(int i=1;i<nums.size();i++){
            temp[i]=temp[i-1]+nums[i];
        }
          return temp;
    }
};
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