我只运行一个简单的代码,但我一直得到"处理完成后退出代码139(被信号11中断:SIGSEGV)" 做一些调试,我发现edge [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;
}
答案 0 :(得分:1)
你的&#39; n&#39;和&#39; m&#39;迭代器变量定义为4,但是&#39; edge&#39;数组的索引介于0和3之间。您的循环将尝试访问边[4],导致索引超出范围和未定义的行为,这可能是您的起始值损坏的原因。
答案 1 :(得分:0)
您已定义距离变量,大小为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;这将导致缓冲区溢出并导致应用程序崩溃。
答案 2 :(得分:-1)
我实际上不知道为什么,但这对我有用:
auto menu = Menu::create(menuButton,moreButton, NULL);
而不是使用#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