简体   繁体   中英

Segmentation fault in c++ code unable to find reason

I am getting segmentation for the last test case (Don't know what it is ) while solving the problem GREATESC. Concept of the problem is basic bfs. Given an undirected graph |V| <= 3500 and |E| <= 1000000 Find the minimum distance between two given vertices. Here's the problem link http://opc.iarcs.org.in/index.php/problems/GREATESC Here's my solution link http://ideone.com/GqTc6k

#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#define Pi 3.14159
#define vi vector<int>
#define pi pair<int,int>
#define si stack<int>

typedef long long int ll;
using namespace std;

bool b[3501][3501]={0};

int main ()
{
    int n,m;
    cin >>n>>m;
    int u,v;
    for (int i  =1;i<= m;i++)
    {
        scanf("%d",&u);
        scanf("%d",&v);
        b[u][v]=b[v][u]=1;
    }
    // input completed.
    int dist[n+1];

    int h,V;
    cin >>h>>V;
    dist[h]=0;
    //cout<<"hero "<<h<<" "<<V<<endl;
    queue<int> q;
    bool  bfs[3501];
    for (int  i=1;i<= n;i++)bfs[i]=1;
    q.push(h);
    bfs[h]=0;
    while (!q.empty())
    {
        int top = q.front();
       // cout<<top<<endl;
        q.pop();
        for (int i = 1 ;i <= 3500;i++)
        {
            if(bfs[i] && b[i][top])
            {
                int x = i;
                dist[i] = dist[top] +1;
                if(x == V){cout<<dist[x]<<endl;return 0;}
                bfs[x]=0;
                q.push(x);
            }
        }
    }
    cout<<0<<endl;
}

You have this:

cin >>n>>m;
...
int dist[n+1];

Hence the array dist may have size less than 3500. But:

        for (int i = 1 ;i <= 3500;i++)
           ...
           dist[i] = dist[top] +1;

This code might be indexing outside of dist .

You seem to need in general to be more careful that when indexing into an array, you're inside the bounds of the array.

Consider using std::vector instead of arrays, then indexing with at to get bounds checking. Or alternatively, manually assert that values are within range:

#include <assert.h>
...
        for (int i = 1 ;i <= 3500;i++)
           ...
           assert(i >= 0 && i <= n && top >= 0 && top <= n);
           dist[i] = dist[top] +1;

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