变量 'n' 周围的堆栈已损坏? C++ VS2010

Stack around the variable 'n' was corrupted? C++ VS2010

所以我正在做一个大学项目,我需要创建一个 'Structures' 的链表。当我向链表添加一个新元素时,我得到了这个错误,这很奇怪,因为我在这样做时甚至没有使用堆栈。 'Structure' 的定义如下:

#ifndef Structure_h
#define Structure_h
#include <stack>
using namespace std;
class Structure
{
public:
    int Integer;
    stack <int> s;
};

#endif

节点定义:

#pragma once
#ifndef Node_h
#define Node_h
using namespace std;
#include "Structure.h"
class Node
{
public:
    Node();
    Structure Str;
    Node *next;
};

#endif

LinkedList.h:

#pragma once
#ifndef LinkedList_h
#define LinkedList_h
using namespace std;
#include "Node.h"
class LinkedList
{
public:
    LinkedList();
    int size;
    void add(int a);
    Node *Current;
    Node *Start;
};

#endif

LinkedList.cpp:

#include "LinkedList.h"
#include <iostream>
LinkedList::LinkedList()
{
    Node FirstNode;
    Start = Current = &FirstNode;
    cout << "Start = " << Start->Str.Integer << endl;
    cout << "Current = " << Current->Str.Integer << endl;
}
void LinkedList::add(int a)
{
    Node n;
    n.Str.Integer = a;
    Current->next = &n;
    Current = Current->next;
    cout << Current->Str.Integer;
}

现在,每当我创建一个新的 LinkedList 并向其添加内容时,我都会收到此错误。 我感觉好像我以某种方式错误地使用了 Stack,但不确定为什么。 提前谢谢你。

在这个方法中:

void LinkedList::add(int a)
{
    Node n;
    n.Str.Integer = a;
    Current->next = &n;
    Current = Current->next;
    cout << Current->Str.Integer;
}

您添加为 next 局部变量 n,它将被销毁一次 add returns。这是未定义的行为。你应该使用Node* n = new Node;,不要忘记释放。

[编辑]

这同样适用于代码中的其他地方,您可以在这些地方获取指向局部变量的指针并将其存储为列表节点。

你有:

void LinkedList::add(int a)
{
    Node n;
    n.Str.Integer = a;

    Current->next = &n;
    // Here, you are storing a pointer to a local variable.
    // The pointer becomes a dangling pointer when the function returns.


    Current = Current->next;
    cout << Current->Str.Integer;
}

使用动态分配的Node

void LinkedList::add(int a)
{
    Node* n = new Node;
    n->Str.Integer = a;
    Current->next = n;
    Current = Current->next;
    cout << Current->Str.Integer;
}