正在释放的C ++指针未分配***在malloc_error_break中设置断点以进行调试

时间:2018-02-19 07:03:37

标签: c++11 pointers reference pass-by-reference pass-by-pointer

我一直收到这个错误。我知道什么功能导致它,但不知道如何解决它。从post这句话在线查询:

  

您需要将指针传递给动态分配的对象,或者让自己的指针链接到您的chainLink类。

然而,当我尝试传递字符串指针时。错误仍然突然出现。这是我的代码。

#include <iostream>
#include "MWTNode.h"
#include "MWT.h"
using namespace std;

int main() {
MWT t;
string str ="abc";
string* strPtr = &str;
t.insert(strPtr);
std::cout << "Hello, World!" << std::endl;
return 0;
}


#include "MWTNode.h"
class MWT {
public:
MWTNode *root;
string find(const string &);
void insert(const string* string);

};
void MWT::insert(const string* word) {
MWTNode* curr = root;
MWTNode newNode;
string w = *word;
for (int i = 0; i < word->length(); i++) {
    const char c = w[i];
    if (curr->children.find(c) == curr->children.end()){

        //curr->children[c]= MWTNode();
        //node->frequency=node->frequency+1;
    }
    curr = &(curr->children[c]);
}
curr->flag = true;
}



#include <unordered_map>
#include <vector>
#include <string>
#include <sstream>
#include <set>
using namespace std;

class MWTNode {
public:
unordered_map<char, MWTNode> children;
string value;
bool flag;
int frequency;

MWTNode(const string &);
MWTNode(const char c);
MWTNode();
void setFrequency ();
int getFrequency ();

};


MWTNode::MWTNode(const string &val) {
value = val;
flag = false;
frequency = 0;
}

MWTNode::MWTNode(const char c) {
value =c;
flag = false;
frequency = 0;
}

MWTNode::MWTNode() {
value ="";
flag = false;
frequency = 0;
}

1 个答案:

答案 0 :(得分:1)

让我们重点介绍您展示的几行代码

class MWT {
public:
MWTNode *root;
// ...
};

因为你将成员变量root声明为指针。

void MWT::insert(const string* word) {
MWTNode* curr = root;
// ...
}

在上文中,您curr指向root指向的位置。

但是 你永远不会让root指向任何地方! MWT::root变量未初始化,并且具有不确定值。在没有初始化的情况下以任何方式使用此指针将导致undefined behavior

是的,您使用此指针,因为您在curr函数内取消引用MWT::insert

有点不清楚你在做什么(对我而言)但是你需要确保root(因此curr)在尝试取消引用之前是一个有效的指针它