我只运行一个简单的代码,但我不断得到"进程完成,退出代码 139(被信号 11 中断:SIGSEGV("做一些调试,我发现 edges[0].start 的值不知何故变成了 -2147483644。我发现这种行为很难解释,并且仍在尝试找出我哪里出错了,但我什至没有更新任何边缘值!无论如何,无论你能给我什么提示,都会受到极大的重视。您将在下面找到代码。提前感谢!温馨的祝愿
#include <stdio.h>
#include <climits>
#include "Utils.h"
struct edge {
int start;
int end;
int weight;
};
int main() {
int n = 4;
int m = 4;
edge edges[4] = {
{2,4,5},
{4,1,6},
{1,3,8},
{3,2,-3}
};
int v,e;
int distance[4];
// Step 1: initialize graph
for(v = 0; v < n; v++){
distance[v] = INT_MAX;
}
distance[0] = 0; //source
// Step 2: relax edges repeatedly
for(v = 0; v < n; v++){
for(e = 0; e < m; e++){
if(distance[edges[e].start] + edges[e].weight < distance[edges[e].end] ){ //relax
distance[edges[e].end] = distance[edges[e].start] + edges[e].weight;
}
}
}
// Step 3: check for negative-weight cycles
for(e = 0; e < m; e++) {
if (distance[edges[e].start] + edges[e].weight < distance[edges[e].end]) { //shouldn't be able to relax
std::cout << "Negative cycle detected, please declare war to Paraguay";
}
}
for(v = 0; v < n; v++){
std::cout << distance[v] << std::endl;
}
return 0;
}
您的 'n' 和 'm' 迭代器变量定义为 4,但 'edges' 数组的索引介于 0 和 3 之间(含 0 和 3(。您的循环将尝试访问 edge[4],导致索引超出范围和未定义的行为,这可能是起始值损坏的原因。
您已定义大小为 4 的距离变量
int distance[4];
而边缘数组的值为:
edge edges[4] = {
{2,4,5},
{4,1,6},
{1,3,8},
{3,2,-3}
};
您正在使用 edge structure
的值来访问每个distance array.
的单元格边的值范围为 -3 到 8,而距离的值范围为 0 到 3;这将导致缓冲区溢出,并导致应用程序崩溃。
我实际上不知道为什么,但这对我有用:
#include <iostream>
struct edge {
int start;
int end;
int weight;
};
int main() {
int n = 4;
int m = 4;
const edge edges[4] = {
{2,4,5},
{4,1,6},
{1,3,8},
{3,2,-3}
}; /* <= for my surprise, I'm not get error with this
* for indexes of distance[something]
*/
int v,e;
int distance[4];
// Step 1: initialize graph
for(v = 0; v < n; v++){
distance[v] = 214748364; // <== with this get fixed
}
distance[0] = 0; //source
// Step 2: relax edges repeatedly
for(v = 0; v < n; v++){
for(e = 0; e < m; e++){
if(distance[edges[e].start] + edges[e].weight < distance[edges[e].end] ){ //relax
distance[edges[e].end] = distance[edges[e].start] + edges[e].weight;
}
}
}
// Step 3: check for negative-weight cycles
for(e = 0; e < m; e++) {
if (distance[edges[e].start] + edges[e].weight < distance[edges[e].end]) { //shouldn't be able to relax
std::cout << "Negative cycle detected, please declare war to Paraguay";
}
}
for(v = 0; v < n; v++){
std::cout << distance[v] << std::endl;
}
return 0;
}
而不是使用distance[v] = INT_MAX;
简单地使用distance[v] = 214748364;
或不太接近INT_MAX
的东西,我得到这个输出:
0
8
13
16
Press <RETURN> to close this window...