Unable to correctly convert QString to wchar_t
First of all, I am sorry for my English, I will try to explain my problem below:
I'm having difficulties using wchar_t after it is converted from QString.
Below I have created an example that helps to reproduce the problem:
@//create instance of QString QString qString="123456"; //create variable to hold converted QString wchar_t *someVar=new wchar_t[qString.size()+1]; //copy QString to allocated variable qString.toWCharArray(someVar); //set last caharacter to null terminator someVar[qString.size()]=L'\0'; //create another variable wchar_t *anotherVar=new wchar_t[qString.size()+1]; //copy above allocated variable to this one wcscpy(anotherVar, someVar); //cleanup delete someVar; delete anotherVar;@
When I run this code with valgrind I get following error: Invalid read of size 8 on this line: wcscpy(anotherVar, someVar);
Also enabling track origins gives this error as well: Address 0x146a21a8 is 24 bytes inside a block of size 28 alloc'd pointing to this line: wchar_t *someVar=new wchar_t[qString.size()+1];
Could you please, help me to resolve this?
Any help is highly appreciated.
Thanks in advance!
PS: I tried above code on 32 bit and 64 bit Linux
Your code looks okay to me, but you can try something like this:
@//On systems with sizeof(wchar_t) == 2
const wchar_t someVar = (const wchar_t) qString.utf16();
//On systems with sizeof(wchar_t) == 4
QVector<uint> ucs4string = qStringto.Ucs4();
const wchar_t someVar = (const wchar_t) ucs4string.constData();
wchar_t *anotherVar = new wchar_t[wcslen(someVar)+1];
Could this be related to the following bug: https://bugs.kde.org/show_bug.cgi?id=307828 ?
I can't find anything wrong with your code (except that an exception in the anotherVar-"new" will leak the memory allocated for someVar)
MuldeR - Thanks for helping. I tried suggested code, but it also gives errors in valgrind.
Tannin - I also started to suspect some kind of bug. So I installed Ubuntu 10.04 32 bit in VirtualBox and this time valgrind did not show any errors (with libqt4-dev installed from repositories). I was trying on 12.04 32 and 64 bits up to yesterday.
On 12.04 gcc version is 4.6.3 and valgrind version is 3.7.0
On 10.04 gcc version is 4.4.3 and valgrind version is 3.6.0