Question

I'm trying to wrap libssh2 in Qt, and have the following code:

const char* username = inUsername.toLocal8Bit().data();
const char* password = inPass.toLocal8Bit().data();

Problem is, that username and password doesn't connect to the system. Why?

Because, according to the debugger,

username  "5.1p1 Debian-6ubuntu2"
password  "5.1p1 Debian-6ubuntu2"

Those are not the values I've given for the username or password. I've tried toAscii, toLatin1, and appending (or not) the .data(). Still, I get these values, instead of the expected values. I'm on Windows, which is why it's even more troubling, since, as far as I can tell, nothing I have was compiled on Debian or Ubuntu.

What's going on here?

Was it helpful?

Solution

This code:

const char* username = inUsername.toLocal8Bit().data();

is equivalent to this:

const char * username;
{
    const QByteArray l8b = inUsername.toLocal8Bit();
    username = l8b.data();
}

Do you see what's going on? By the time the statement has executed, the temporary QByteArray has been deleted by the compiler again. Since data() only returns a pointer to the internal QByteArray buffer, username now points to deleted/freed memory.

To solve the problem, make username and password QByteArrays instead of const char*s, and use username.data(), password.data() instead where you used username, password before.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top