weixin_45135245
WYJ开怪
采纳率77.8%
2020-09-07 10:33

QT使用QTcpSocket创建的客户端,出现野指针,怎么解决。

已采纳

mainwindow.cpp

#include"QDebug"
#include"QRadioButton"
#include"Login.h"
#include"string.h"
#include <QtNetwork>
#include<QTcpSocket>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //建立套接字
    QTcpSocket *client = new QTcpSocket(this);
    Login login;
    //连接服务器
    client->connectToHost(QHostAddress("192.168.3.17"), 1234);
    client->open(QIODevice::ReadWrite);
        connect(ui->Login_pushButton,&QPushButton::clicked,[&](){
        if(ui->Teacher_Login_radioButton->isChecked() == true){

            //赋值id
            login.id = ui->User_ID_LienEdit->text().toInt();
            //赋值名字
            const char *strName = ui->User_Name_LienEdit->text().toLatin1().data();//用QStirng类型的toLatin1成员函数获得QByteArray类,然后通过QByteArray的data()成员函数获得这个数组的首地址
            strcpy_s(login.UserName,ui->User_Name_LienEdit->text().size()+1,strName);

            //赋值密码
            const char *strPW = ui->User_PassWord_LienEdit->text().toLatin1().data();//用QStirng类型的toLatin1成员函数获得QByteArray类,然后通过QByteArray的data()成员函数获得这个数组的首地址
            strcpy_s(login.PassWord,ui->User_Name_LienEdit->text().size()+1,strPW);
            qDebug()<<"工号为"<<login.id<<"的"<<login.UserName<<"老师登入"<<endl;

            const char * sendBuf = (const char*)&login;
            client->write(sendBuf);

            char recvBuf[1024] = {};

            int recvLen = client->read(recvBuf, sizeof(dataHeader));
            if (recvLen <= 0)
            {
                qDebug() << "已和服务器断开连接" << endl;
            }
            else
                {
                    dataHeader* dheader = (dataHeader *)recvBuf;
                     client->read(recvBuf + sizeof(dataHeader), dheader->datalength - sizeof(dataHeader));
                    LoginResult* ret = (LoginResult*)recvBuf;

                    if (ret->result == 1)
                    {
                        qDebug() << "登入成功" << endl;
                    }
                    else
                    {
                        qDebug() << "登入失败,请重新登入" << endl;
                    }
                }
        }

    });

}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • weixin_38739598 芒种、 7月前

    哪里出现野指针,调试报错上传一下问题

    点赞 1 评论 复制链接分享