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?

Answers


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!

Need Your Help

GIT: How to get rid of the annoying CRLF message on msysgit (windows)?

git newline git-gui core.autocrlf

Practically everytime I stage a textfile (that's most of em), I get the message from git gui (I use msysgit) that It replaced (or is about to) line endings with CRLF's. Obviously I want that (and t...

Print comma separated items without newline

python python-3.x printing

I thought I was copying word for word from a previous question/answer, but, I don't get what I wanted.