簡體   English   中英

C ++代碼中的分段錯誤無法找到原因

[英]Segmentation fault in c++ code unable to find reason

解決問題GREATESC時,我正在對最后一個測試用例進行細分(不知道它是什么)。 問題的概念是基本的bfs。 給定無向圖| V | <= 3500和| E | <= 1000000查找兩個給定頂點之間的最小距離。 這是問題鏈接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;
}

你有這個:

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

因此,數組dist大小可能小於3500。但是:

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

該代碼可能在dist之外建立了索引。

通常,您似乎需要更加小心,因為在索引到數組時,您位於數組的范圍之內。

考慮使用std::vector而不是數組,然后使用at進行索引以進行邊界檢查。 或者,手動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