Details
-
Bug
-
Resolution: Invalid
-
Not Evaluated
-
None
-
6.6.1
-
None
-
Happens on any system, Ubuntu 22.04, Windows XP, 7, 10. I use mingw to build for win32.
Description
Before I start. The issue I describe happens in ALL versions of Qt. I tested it on 4.8.4, 5.15.16 and 6.6.1 .
When I need a char-pointer to the UTF-8 representation of a QString, I do it like this:
const char * foo = myQString.toUtf8().constData();
But it appears that the memory allocated by toUtf8() is freed too early and thus available for reuse! Which happens on the next call to toUtf8(), for example.
const char * foo = myQString.toUtf8().constData();
const char * bar = anotherQString.toUtf8().constData();
I have seen that anotherQString.toUtf8() uses the exact same memory, and hence, foo does not point to the expected UTF-8 representation of myQString.
So, what is the 'lifetime' of the Memory allocated by toUtf8()?
Until the next call to toUtf8()? How can I be sure the memory is not touched by another process or thread?
As a 'solution' I store the result of toUtf8() in a local QByteArray, but it feels uncomfortable knowing that many libraries and Qt itself use myQString.toUtf8().constData(); frequently too!
I have attached an example project showing what happens.
Example of program output:
Qt version: 6.6.1
OS: Linux
show bug
1 foo=foo (0x0x5e8acd663910)
2 foo=bar (0x0x5e8acd663910)
3 bar=bar (0x0x5e8acd663910)
foo memory is reused/overwitten by bar UTF-8 data!
show postponed fix
1 foo=foo (0x0x5e8acd663910)
2 foo=foo (0x0x5e8acd663910)
3 bar=bar (0x0x5e8acd663960)
foo is OK
4 foo=foo (0x0x5e8acd663910)
5 bar=qux (0x0x5e8acd663960)
6 qux=qux (0x0x5e8acd663960)
bar memory is reused/overwitten by qux UTF-8 data!
show permanent fix
1 foo=foo (0x0x5e8acd663910)
2 foo=foo (0x0x5e8acd663910)
3 bar=bar (0x0x5e8acd663960)
foo is OK
4 foo=foo (0x0x5e8acd663910)
5 bar=bar (0x0x5e8acd663960)
6 qux=qux (0x0x5e8acd663990)
bar is OK