在执行find()操作后,向量元素数据已损坏

时间:2019-05-19 14:04:07

标签: c++ stdvector corruption

我正在使用C ++构建一个编译器。在语义分析期间,我遇到了数据损坏问题。我有一个functionList向量,其中存储了包含函数名称,类型,参数和语句块的函数列表。

在整个源代码中首次遇到该函数时,都会在functionList向量中对其进行跟踪:

virtual void Visit(AST::FunctionDeclare& p_node) override {
    if (ST->Insert(p_node.getName(), p_node.getType())) {
        p_node.getParams()->Accept(*this);
        p_node.getBlock()->Accept(*this);

        if (p_node.getType() != typeStack.top()) {
            Error("Function return type is incorrect!");
            return;
        } else {
            typeStack.pop();
        }

        // Keep track of this declared function to run it when called.
        AST::FunctionDeclare newNode = p_node;
        functionList->push_back(&newNode);
    } else {
        hasErrored = true;
    }
}

验证函数调用时,下面的“查找”操作导致提到的数据损坏:

virtual void Visit(AST::FunctionCall& p_node) override {
    // Verify function exists
    if (ST->Lookup(p_node.getName()) == "") {
        std::string errorText = "No function with name '" + p_node.getName() + "' was found.";
        Error (errorText);
        return;
    }

    // Locate and setup required function
    AST::FunctionDeclare *pFunc = nullptr;
    // Find required function declaration
    for (auto tempFunc : *functionList) {
        if (tempFunc->getName() == p_node.getName()) // got it!
            pFunc = tempFunc;
    }

“查找”操作执行以下操作:

    // Returns type if found, empty if not
    std::string Lookup (std::string p_name) {
        for (int i = 0; i < _scopeVector.size(); i++) {
            if (_scopeVector[i]->find(p_name) == _scopeVector[i]->end()) {
                // No match yet
            } else {
                return _scopeVector[i]->find(p_name)->second; // return var type
            }
        }
        std::cerr << "Type name " << p_name << " not found in all of stack" << std::endl;
        return "";
    }

当我执行简单的find()动作时,似乎好像正在跟踪丢失的内存位置。我没想到此操作会在设置数据后更改数据,我错了吗?在这种情况下,什么是避免内存损坏的正确方法?

1 个答案:

答案 0 :(得分:2)

您将在此处存储指向局部变量的指针:

AST::FunctionDeclare newNode = p_node;
functionList->push_back(&newNode);

函数返回时,&newNode是无效的,因为newNode是局部变量。

如果您的目标是共享指针,请使用std::vector<std::shared_ptr<AST::FunctionDeclare>>

相关问题