2 [main] hw3 10368 cygwin_exception::open_stackdumpfile:将堆栈跟

2 [main] hw3 10368 cygwin_exception::open_stackdumpfile: Dumping stack trace to hw3.exe.stackdump

本文关键字:stackdumpfile open 堆栈 exception hw3 10368 cygwin main      更新时间:2023-10-16
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <utility>
using namespace std;
struct node
{
int level = -1;
int value = -5;
node *left;
node *right;
};
int array[100][100];
void storetree(node *root, int val);
void printtree();
int main()
{
cout << " u there?" << endl;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
array[i][j] = -5;
}
}
ifstream file1;
ifstream file2;
file1.open("tree1.txt");
file2.open("graph1.txt");
node root;
node *root1;
int val1;
int randval;
file1 >> val1;
root.level = 0;
root1->level = 0;
root.value = val1;
root1->value = val1;
array[0][0] = val1;
cout << "made it" << endl;
root1->left->value = -5;     // <-- Error happens here
root1->right->value = -5;
root1->left->level = -5;
root1->right->level = -5;

因此,当我访问root1->left->value时,会发生错误,并且出现堆栈转储错误。

以我编写的方式访问 root1->左>值是不可能的吗?通过打印语句,我推断出这是错误。我不太了解指针,希望得到帮助。:)

我在下面注释了您的源代码:

...
// Allocate an actual instance of your 'node' struct (local variable, on the stack)
node root;
// This allocates a POINTER variable, which just contains an address.
// The compiler knows that 'root1' will point at 'node' types.
// Note that you've only created a pointer variable here; NOT an actual node.
// Further, you haven't initialized it, so its value is "undefined"
// (you can't assume you know what its value is ... it could be anything).
node *root1;
...
// Set 'level' on the root node to zero
root.level = 0;    // This is OK, because root is an actual 'node' struct instance
// Set 'level' ON THE NODE THAT 'root1' POINTS TO to zero
root1->level = 0;  // This is not OK, because root1 is a wild (uninitialized) pointer

这是你的第一个问题。你创建了一个指针,但你没有指向任何东西。root1的值(即它引用的地址)是未定义的(可以是 NULL,可以是该变量所在的内存中的任何内容)

最好在定义局部变量时立即对其进行初始化。未初始化的变量可以具有未定义的值,这可能会为您的生活增加无数小时的调试时间,其中程序的每次运行都与上次运行不同。嘭。

如果在定义变量时尚未准备好分配实际值, 将其设置为某个已知值,例如 0、nullptr等。如果你以后忘记设置它,你的程序至少每次都会做同样的错误事情。

node *root1 = nullptr;  // (...or maybe your compiler uses "NULL" or "(void *)0"...)

看起来您将根据从输入文件中读取的任何内容构建节点树? 如果是这样,那么您几乎肯定会动态分配节点结构,因为您无法提前知道需要多少节点结构。

// Allocate and initialize a new node struct (on the heap)
root1 = new node();
// Set 'level' ON THE NODE THAT 'root1' POINTS TO to zero
root1->level = 0;  // Yay, now this works

变量root1现在包含新分配的node结构的地址。其余代码应该从那里开始工作。

只是提醒一下,一个"正确"的程序(例如,一个不泄漏内存的程序)最终应该在调用new返回的每个指针上调用delete。 此外,在构建动态分配的node对象树时,请记住这一点;完成后,您需要对它们中的每一个调用delete(除了 root,它不是动态分配的)。