Pergunta

I'm trying to create a server using qttcpserver. My code was written for this example. The only difference is that I also used the thread pool. I have a form on which there are two buttons. The first button creates an object of my class server, and the second removes. As is clear buttons are responsible for switching on and off the server. I want to run a server on different ports. So, I need to create multiple class objects on my server and pass as a parameter to the constructor of the desired port.

To give you a better understanding of the code of my buttons.

class FormServer {
...
private:
   MyServer * server;
public:
void start() {
   server = new MyServer();
}
void stop() {
   delete server;
}
}

This is an example of an example when I run the server on one port. Here's an example for different ports.

class FormServer {
    ...
private:
QList<unsigned> ports;
QVector<MyServer *> server;
public:
void start() {
    for(auto i = ports.begin(); i != ports.end(); i++) {
        server.push_back(new MyServer(*i)); //port passed as a parameter
    }
}
void stop() {
    for(auto i = server.begin(); i != server.end(); i++) {
        delete *i;
    }
}
}

In the first example, everything works fine. A second has a big problem. Here is an example problem.

start(); //ok
stop(); //ok
start(); //ok
stop(); //error

Watching debugging and see that errors occur in a row delete *i (Unhandled exception at 0x01033862 in server.exe: 0xC0000005: Access violation reading address 0x0000000C.)

Then why is it only occurs when the function is called the second stop, and at first everything is fine?

Please help me fix the problem.

P.S Sorry, that is not a complete example code, because it is very large and parse that to be very difficult. Also Sorry for my English.

Foi útil?

Solução

You have two issues in here, one of which is subtle, but still:

  • You are writing the delete algorithm yourself for the elements rather than using qDeleteAll. It is better not to reinvent the wheel.

  • You are not removing the elements from the container, just delete them.

Therefore, I would be writing something like this if I were you:

#include <QtAlgorithms>

...

void stop() {
    qDeleteAll(server);
    server.clear();
}

Please check out the QtAlgorithms documentation for details.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top