3

Issue comes up when i try to unload plugin that is loaded and load a new one. So both plugins are loaded correctly, but when switching them (first is loaded, second is unloaded and viceversa) my app crashes. What can be the problem ?

First what i'm doing i try to unload a plugin stored into a QList of QPluginLoader, then i check (depdend on id(integer number) passed from a special menu for loading plugins ) what plugin to load. First load is well (first plugin is loaded, nothing at this point to unload) , second load (unload first plugin, second is loaded), at third load i get crash

void MainWindow::loadPluginUsingId (int plugin_id) {

        foreach (QPluginLoader* pluginLoader, plugins) {        
                 pluginLoader->unload();
                 delete pluginLoader;
               }

         switch (plugin_id) {

           case 0 : {

            foreach (QString fileName, pluginDir.entryList(QDir::Files)) {
               if (fileName == fullNameOfPlugins.value(plugin_id)) {
                     QPluginLoader* pluginLoader = new QPluginLoader(pluginDir.absoluteFilePath(fileName));
                     QObject *plugin = pluginLoader->instance();

                     IndicatorInterface *indicator = qobject_cast<IndicatorInterface*>(plugin);
                     indicator->initIndicator();
                     plugins.append(pluginLoader);
                 }
             }
         }

         break;
          case 1 : {

             foreach (QString fileName, pluginDir.entryList(QDir::Files)) {

                 if (fileName == fullNameOfPlugins.value(plugin_id)) {

                       QPluginLoader* pluginLoader = new          QPluginLoader(pluginDir.absoluteFilePath(fileName));
                       QObject* plugin = pluginLoader->instance();
                       PlotterInterface *plotter = qobject_cast<PlotterInterface*>(plugin);
                       plotter->initPlotter();
                       plugins.append(pluginLoader);
                     }
                 }
            }
         break;
           default :
               break;
           }
 }

1 Answers1

7
    foreach (QPluginLoader* pluginLoader, plugins) {        
             pluginLoader->unload();
             delete pluginLoader; // this could be your problem
           }

You need to remove the dangling pointer from the plugins list. Failure to do that would result in what you're describing.

Try this:

while (!plugins.isEmpty()) {        
   QPluginLoader* pluginLoader = plugins.takeFirst();
   pluginLoader->unload();
   delete pluginLoader;
}
cgmb
  • 4,284
  • 3
  • 33
  • 60