0

If I run this constructor

USB::USB(){
    serialPort = new QSerialPort();
    serialPortInfo = new QSerialPortInfo();
}

From this class

#include <QSerialPort>
#include <QSerialPortInfo>

class USB {
public:
    USB();
private:
    QSerialPort* serialPort;
    QSerialPortInfo* serialPortInfo;
};

Then I got the error

The program has unexpectedly finished.

If I comment the code

USB::USB(){
    //serialPort = new QSerialPort();
    //serialPortInfo = new QSerialPortInfo();
}

Then I get no errors at all. Why does this happens? I have missed something?

I'm running QT5 at Windows 10.

This gives no errors. Getting information about the COM ports works.

USB::USB(QSerialPort* serialPort, const QSerialPortInfo& serialPortInfo){
    this->serialPort = serialPort;
    this->serialPortInfo = serialPortInfo;
}
euraad
  • 2,467
  • 5
  • 30
  • 51
  • The worst problem with undefined behavior is sometimes it will appear to work even when your program is broken. – drescherjm Aug 13 '21 at 13:43
  • @drescherjm Thank you for your reply. I will test and see if I can open a COM port. Giving you a reply later. – euraad Aug 13 '21 at 14:57
  • Since the little bit of code you provide looks fine, my guess is that you have a memory leak/stomping/issue elsewhere in the code and the UB you're seeing is a result of that, not QSerialPort itself. Time to fire up the debugger and/or memory analyzer. – Maxim Paperno Aug 14 '21 at 04:01
  • @MaximPaperno I notice that QSerialPort does not allow to create a reference. Only using keyword `new`. – euraad Aug 14 '21 at 19:17
  • By definition a reference must refer to something which already exists, so I don't know what you mean by "create a reference." One could create objects on the stack or the heap, which is perhaps what you're referring to. I think you need to show more code. For example you don't parent the QSerialPort which you created in `USB()` c'tor, yet you also don't show where you delete that instance (which is clearly wrong). It's also not clear why you choose to create QSerialPortInfo on the heap vs. stack (which is fine but again you need to explicitly delete it when done). – Maxim Paperno Aug 14 '21 at 20:14

0 Answers0