[英]Stack around the variable [string] is corrupted c++
创建一个程序,该程序将读取邻接矩阵,并使用该矩阵和顶点计数创建图形,然后使用必要的信息为GraphViz编写.dot文件。
每次我尝试运行该程序时,最后访问的字符串fileNameX变量总是损坏的(变量fileName [x]周围的堆栈损坏了)。 我不知道我在做什么错,为什么会这样,因为我以前从未遇到过这个错误。 有任何想法吗?
值得一提的是,当我运行该程序时,它不会在目录中创建或打开相关文件,但我认为这是此问题的一部分。 如果没有,请随时纠正我。
图类的主要功能和打印功能如下。
#include <fstream>
#include "graph.h"
#include "string"
using namespace std;
int main()
{
ifstream infile;
infile.open("input.txt");
char c;
int i, count = 0;
string fileName1 = "graph0.dot", fileName2 = "graph1.dot", fileName3 = "graph2.dot";
while (infile>>c)
{
bool adjacencies[10][10];
infile.get(c);
i = (int)c;
// Loops looking for 1s and 0s to "store" in adjacency matrix
for (int x = 0; x < i; x++)
{
for (int y = 0; y < i; y++)
{
infile.get(c);
while (c != '1' && c != '0')
infile.get(c);
if (c == '1')
adjacencies[x][y] = true;
else if (c == '0')
adjacencies[x][y] = false;
}
}
graph G(adjacencies, i);
if (count == 0)
G.GraphVizOut(fileName1);
else if (count == 1)
G.GraphVizOut(fileName2);
else if (count == 2)
G.GraphVizOut(fileName3);
count++;
}
system("pause");
return 0;
}
// Notes paths between vertices with "X -- Y" notation.
void graph::CreateEdges(std::ofstream &outfile)
{
// If matrix is symmetrical, graph is undirected
if (isSymmetrical == true)
{
for (int x = 0; x < VertCount; x++)
{
for (int y = x; y < VertCount; y++)
{
if (adjacency[x][y] == true)
outfile << x << " " << "--" << y << "\n";
}
}
}
// If matrix is not symmetrical, graph is directed
else
{
for (int x = 0; x < VertCount; x++)
{
for (int y = 0; y < VertCount; y++)
{
if (adjacency[x][y] == true)
outfile << x << " " << "--" << y << "\n";
}
}
}
return;
}
// Creates the file, writes header information, and then calls CreateEdges above necessary info write to it
void graph::GraphVizOut(std::string filename)
{
std::ofstream VizOut;
VizOut.open(filename);
VizOut << "// Trey Brumley \n";
VizOut << "// File created by C++ BST Project \n";
VizOut << "graph G { \n";
CreateEdges(VizOut);
VizOut << "} \n";
VizOut.close();
return;
}
infile.get(c);
i = (int)c;
这将从文件中读取一个字符,并将其(通常为ASCII) 值存储在i
。 ASCII数字在[48,57]范围内,因此当从0
到i
对其进行索引时, adjacencies
数组中的写越界。
要快速解决:请转换ASCII值,以便数字正确。
infile.get(c);
i = c - '0';
要正确修复它:只需让std::istream
读取实际的int
。
infile >> i
if(i < 1 || i > 10) {
// Invalid input !
}
为了防止它:使用std::array
而不是C样式的数组。
std::array<std::array<bool, 10>, 10> adjacencies;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.