Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

runtime error: addition of unsigned offset to 0x129000a0 overflowed to 0x12900088

Tags:

c++

Here is my code.

#include <iostream>
#include <vector>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n;
    cin >> n;
    vector<string> v;

    for(int i=0; i<n; i++)
    {
        string temp;
        cin>>temp;
        v.push_back(temp);

        //if(v.size() == 1)
        //{
        //    continue;
        //}

        //cout << i << endl;
        //cout << endl;

        //cout << v.size();

        int k = i;
        while(v[k-1].length() > v[k].length() && k>-1)
        {
            swap(v[k], v[k-1]);

            k--;
        }
        //cout << endl;
    }

    bool check = true;
    for(int i=0; i<v.size()-1; i++)
    {
        //cout << v[i] << endl;
        //cout << v[i+1] << endl;

        if (v[i+1].find(v[i]) != std::string::npos)
        {
            //std::cout << "found!" << '\n';
            continue;
        }

        //cout << "false" << endl;
        check = false;
    }

    if(check == true)
    {
        cout << "YES" << endl;
        for(int i=0; i<n; i++)
        {
            cout << v[i] << endl;
        }
    }
    else
    {
        cout << "NO" << endl;
    }
}

What’s the reason for this error?

The input was:

100
npugmvzdgfnzyxuyfwbzwktiylhvhwgeqauolidpnbemhgbunpefzsltewkxdcrzxgvmkb
bezfumiguzafxghvcfqmwpopxvazctlftelveayycypjckooxeehyk
ingenqhogs
elhnhxjwrytbmmqdwwrivvljybhnwfgwhvdgjqgqgvunuemdtrgpyvaanovheqbupamzrjxh
rpvktlmyxfshahfgunrhuqtosysymfjruqlzdooauuihtchzqgyrhcoxbtoorkxkwakvdkiakitlqfbgz
tnrnpghjmqumbzfnztiijgwkiygyfevfebuammkwnoinqvhhlsuoqtfkazqhlnuqtthudhhovjqiuykwqtck
mloehzniuwyakgwmopfgknpoiuiyewijmoefjjjsdimkisugehwqefcx
tthmaxtahimxxts
fspoetalxgcgowhjtanerjpqnen
hefsyokneekdgpbicss

It works for other cases.

Diagnostics detected issues [cpp.clang++-diagnose]: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\include\vector:1802:11: runtime error: addition of unsigned offset to 0x129000a0 overflowed to 0x12900088

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\include\vector:1802:11 in

like image 934
eskimo ice Avatar asked Jun 13 '18 19:06

eskimo ice


1 Answers

Whats the reason for this error:

You set i to 0

int i=0;

Then you set k to 0.

int k=i;

Then you use k-1 to index std::vector<std::string> v.

while(v[k-1].length()

k-1 is -1, but it gets worse. std::vector::operator[] casts the parameter to an unsigned type, producing an impossibly huge, not-at-all-valid index.

No bounds checking is performed with std::vector::operator[] and you end up treating memory you don't own as if it were a validly constructed std::string.

like image 63
Drew Dormann Avatar answered Mar 19 '23 17:03

Drew Dormann