vendredi 23 septembre 2022

How do I fix an invalid write using the vector library?

I'm working on an assignment, and I'm running into an error where I run my code I get "malloc(): invalid size (unsorted) aborted (core dumped)". Using Valgrind, I can see that the error is an "Invalid write of size 8" happening when I am calling emplace_back() but I have no idea why it is causing this issue. There is much more code than this, but I've tried to include only what I think is relevant to the issue.

std::vector<REG::REG_node *> my_LexicalAnalyzer::matchOneChar(std::vector<REG::REG_node *> S, char c)
{
    std::vector<REG::REG_node *> s1;
    for (int i = 0; i < S.size(); i++)
    {
        if (S[i]->first_label == c && !contains(s1, S[i]->first_neighbor))
            s1.emplace_back(S[i]->first_neighbor);
        if (S[i]->second_label == c && !contains(s1, S[i]->second_neighbor))
            s1.emplace_back(S[i]->second_neighbor);
    }

    if (s1.empty())
        return s1;

    bool changed = true;
    std::vector<REG::REG_node *> s2;

    while (changed)
    {
        changed = false;

        for (int i = 0; i < s1.size(); i++)
        {
            s2.push_back(s1[i]);

            if (s1[i]->first_label == '_' && !contains(s2, s1[i]->first_neighbor))
                s2.push_back(s1[i]->first_neighbor);
            if (s1[i]->second_label == '_' && !contains(s2, s1[i]->second_neighbor))
                s2.push_back(s1[i]->second_neighbor);
        }

        if (s1 != s2)
        {
            changed = true;
            std::vector<REG::REG_node *> empty;

            // Copy s2 into s1 and empty into s2
            copy(s2.begin(), s2.end(), s1.begin());
            copy(empty.begin(), empty.end(), s2.begin());
        }
    }

    return s1;
}
class REG
{
public:
    struct REG_node
    {
        struct REG_node *first_neighbor;
        char first_label;
        struct REG_node *second_neighbor;
        char second_label;
    };
};

This is where the nodes are being allocated.

REG::REG_graph *REG::createREG(char input)
{
    struct REG_node *node1 = new REG_node{nullptr, input, nullptr, '\0'};
    struct REG_node *node2 = new REG_node{nullptr, '\0', nullptr, '\0'};

    node1->first_neighbor = node2;

    struct REG_graph *graph = new REG_graph{node1, node2};
    return graph;
}

Aucun commentaire:

Enregistrer un commentaire