ali
ali

Reputation: 29

Simulating Leach has encounter a problem. Finished with error in omnet++

When running the simulation in omnet++ 5.7 the execution stops suddenly and closes. This is the code that is being run in omnet

auto simulation = getSimulation();
for (i = 1; i <= simulation->getLastComponentId(); i++) {

    int x, y, id;

    //scan the simulation module vector
    mod = (cModule*)simulation->getModule(i);

    if (strcmp(mod->getName(), "node") == 0) {
        id = ((Node*)mod)->myId;
        x = ((Node*)mod)->xpos;
        y = ((Node*)mod)->ypos;
        nodePtr[id] = ((Node*)mod);

        if (id != this->myId) {
            cGate* g;
            char gName1[32], gName2[32];

            // make new gate here
            if (this->hasGate(gName1)) {
                this->gate(gName1)->disconnect();
                this->deleteGate(gName1);
            }

            this->addGate(gName1, cGate::OUTPUT, false);

            // make new gate at other side
            if (mod->hasGate(gName2)) {
                mod->gate(gName2)->disconnect();
                mod->deleteGate(gName2);
            }

            mod->addGate(gName2, omnetpp::cGate::INPUT, false);

            //CHANNEL
            cIdealChannel* ch = NULL;
            this->gate(gName1)->connectTo(mod->gate(gName2), ch);
            g = this->gate(gName1);
            g->setDisplayString(g->getDisplayString());
        }
    }
}

I assume that the last line g->setDisplayString(g->getDisplayString()); is probably where the code breaks. The code repeats in the for loop with i<= simulation->getLastComponentId(). I'm new to Omnet++. Any suggestion to fix this would be helpful.

Thanks.

Upvotes: 0

Views: 331

Answers (1)

Jerzy D.
Jerzy D.

Reputation: 7002

Several things in your code may be source of crashing:

  1. getModule(i) may return nullptr, see OMNeT++ Simulation API, so you should check in the code whether result is not nullptr.
  2. gName1 and gName2 are not set!

Other issues:

  • instead of (Node*)mod use dynamic_cast<Node*)>(mod) and check whether results is not nullptr.
  • instead of strcmp(mod->getName(), "node") == 0 I advice using mod->isName("node") - see OMNeT++ Simulation API
  • if you want to obtain a module whose name is "node", you do not need to manually check the name of every module - there is a useful method getModuleByPath() see OMNeT++ Simulation Manual

Upvotes: 0

Related Questions