Home > database >  runtime error: addition of unsigned offset/UndefinedBehaviorSanitizer: undefined-behavior
runtime error: addition of unsigned offset/UndefinedBehaviorSanitizer: undefined-behavior

Time:07-15

I am not able to find where is my vector going out of bound please help me. this is solution of leetcode question 695.

error :- Line 1034: Char 34: runtime error: addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028 (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

int maxAreaOfIsland(vector<vector<int>>& grid) {
    int n = grid.size();
    int m = grid[0].size(); 
    
    vector<vector<int>> vis(n,vector<int>(m,0));
    int ans =0 ;
    for(int i=0;i<n;i  ) {
        for(int j=0;j<m;j  ) {
            int count  = 0;
            if(grid[i][j]==1 && !vis[i][j]) {
                vis[i][j]=1;
                queue<pair<int,int>> q;
                q.push({i,j});
                count  ;
                while(!q.empty()) {
                    int  a = q.front().first;
                    int  b = q.front().second;
                    q.pop();
                    
                    int r[] = {-1, 1, 0, 0};
                    int c[] = {0, 0, 1, -1};
                    
                    for(int z=0; z<4; z  ) {
                       int x = a   r[z];
                       int y = b   c[z]; 
                       if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) {
                           vis[x][y]=1;
                           q.push({x,y});
                           count  ;
                       }
                    }
                    
                }
                ans = max(ans,count);
            }
        }
    }
    return ans;
}

CodePudding user response:

I am not able to find where is my vector going out of bound please help me

The simplest way(IMO) to find out where you're going out of bounds in the vector is to use std::vector::at instead of std::vector::operator[].

When using at you'll get an out_of_range exception if the index is greater or equal to the size of the vector. For example, use grid.at(i).at(j) instead of grid[i][j] and so on for other as well.

CodePudding user response:

I expect

if(x<n && y<m && grid[x][y]==1 && !vis[x][y]) {

should be

if (x>=0 && y>=0 && x<n && y<m && grid[x][y]==1 && !vis[x][y]) {

Notice in the error addition of unsigned offset to 0x610000000040 overflowed to 0x610000000028. In other words the unsigned offset is negative (when regarded as a signed quantity).

Always be careful mixing signed and unsigned arithmetic.

  • Related