mooky Fare
mooky Fare

Reputation: 97

Global variable contains garbage when push button is clicked

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtDebug>
#include <iostream>
char * ip_ch;
void test(const char* a)
{
    qDebug()<<"test is "<<a;

}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_lineEdit_editingFinished()
{
    QString st_ip_ch=ui->lineEdit->text();
    QByteArray ip_ch_temp = st_ip_ch.toLatin1();
    ip_ch = ip_ch_temp.data();
    qDebug()<<"ip_ch is "<<ip_ch;
    test(ip_ch);
}

void MainWindow::on_pushButton_clicked()
{
    qDebug()<<"when push button ";
    test(ip_ch);
}

The code uses the following UI. I want to type some string in the line input widget like this, and then push the button.

It prints out this:

ip_ch is  123
test is  123

When button is clicked, it prints:

test is  `??`

Why does ip_ch point to garbage?

Upvotes: 0

Views: 71

Answers (1)

ip_ch becomes a dangling pointer as soon as on_lineEdit_editingFinished() returns. That's because you're making it point to a temporary buffer ip_ch_temp that goes out of scope:

ip_ch = ip_ch_temp.data(); // Don't do that!

Since you're coding in C++, you shouldn't be writing C. Store your Latin1 representation by value:

class MainWindow : public QMainWindow {
  QByteArray ip_ch;
  Ui::MainWindow ui;
public:
  MainWindow(QWidget * parent = 0) {
    ui.setupUi(this);
  }
  // no explicit destructor needed!

  void test(const QByteArray & data) { qDebug() << "test:" << data; }

  void on_lineEdit_editingFinished()
  {
    ip_ch = ui.lineEdit->test().toLatin1();
    qDebug() << "ip_ch is" << ip_ch;
    test(ip_ch);
  }

  void on_pushButton_clicked()
  {
    qDebug() << "button was pushed";
    test(ip_ch);
  }
};

Other problems with your code:

  1. #include <QDebug>, not <QtDebug>
  2. #include <QMainWindow>, not <qmainwindow.h>
  3. Most likely, you don't need to derive your dialog from QMainWindow; derive from a QDialog instead.
  4. Don't use a pointer to ui; store it by value instead. That way you have less code that can go wrong: let the compiler manage memory for you. That's what it's for!

Upvotes: 2

Related Questions