Problem with pointers?
-
Hi, I'm using this code below for getting the value of password from the lineEdit to be displayed on QMessageBox:
@char* pass = ui->pass->text().toAscii().data();
QMessageBox::information(0,0, pass);@however, I get an empty message, but when I put ui->pass->text().toAscii().data() instead of pass: it works, and I get the full password value inside the message. so why am I getting this problem? thanks.
-
Hi, and welcome to the Qt Dev Net!
toAscii() constructs a new QByteArray. data() returns the pointer to the QByteArray's internals.
In your code, you did not store the QByteArray anywhere. Therefore, it gets destroyed after line #1, and char* pass contains a dangling pointer.
-
-
[quote author="Xander84" date="1398529302"]Why do you even use a char*, the functions prototype is like:
@
StandardButton QMessageBox::information(QWidget * parent, const QString & title, const QString & text)
@
so you would use it like
@
QMessageBox::information(this, ,"title", ui->pass->text());
@[/quote]you still don't understand what I mean, I just want to store the value to char* correctly without any need to display it
-
ok sorry because you mentioned an example with QMessageBox::information ...
if you just want to use the char array you have to copy it i guess, you can use strcpy or memcpy, I don't know if Qt has some helpers for cleaner c++ usage?
Or just save a reference to the QString, depends on what you are doing with that char* and how often you need to use it.
Storing a copy of the QString (or QByteArray) is the cleanest solution in my opinion. -
[quote author="kaisbs" date="1398529964"]
ok, I understand now why that doesn't work: I shall use @.toStdString().c_str()@ instead of @.toAscii().data()@it's all right now, thanks all for your replies.
[/quote]No, you still have a bug in your code. You might not see any problems now, but that's just a coincidence. Your program will likely crash in the future.@
// 1. Here, you create a temporary std::string and get a pointer to its internal data.
char* pass = ui->pass->text().toStdString().c_str();// 2. Here, the std::string gets destroyed because you did not store it anywhere. So, the pointer in 'pass' is no longer valid.
// 3. Here, you use the invalid pointer. The behaviour is undefined.
QMessageBox::information(0,0, pass);
@You need to make sure that the std::string doesn't get destroyed until you have finished using the pass pointer. You can do this by storing the std::string in a local variable, and then calling c_str() to get the char-pointer from that variable.