简体   繁体   English

C ++代码中的分段错误无法找到原因

[英]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. 解决问题GREATESC时,我正在对最后一个测试用例进行细分(不知道它是什么)。 Concept of the problem is basic bfs. 问题的概念是基本的bfs。 Given an undirected graph |V| 给定无向图| V | <= 3500 and |E| <= 3500和| E | <= 1000000 Find the minimum distance between two given vertices. <= 1000000查找两个给定顶点之间的最小距离。 Here's the problem link http://opc.iarcs.org.in/index.php/problems/GREATESC Here's my solution link http://ideone.com/GqTc6k 这是问题链接http://opc.iarcs.org.in/index.php/problems/GREATESC这是我的解决方案链接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: 因此,数组dist大小可能小于3500。但是:

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

This code might be indexing outside of dist . 该代码可能在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. 考虑使用std::vector而不是数组,然后使用at进行索引以进行边界检查。 Or alternatively, manually assert that values are within range: 或者,手动assert值在范围内:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM