PDA

View Full Version : qDebug string display



zgulser
2nd July 2012, 12:29
Hi,

I have a function like the following;



QString LoggerManager::encryptAes(const char* p_Text, const char* p_key)
{
...

unsigned char* text = new unsigned char((strlen(p_Text) - 1)*sizeof(char));

for(int i=0; i < (strlen(p_Text) - 1); i++)
{
text[i] = p_Text[i];
}

...

qDebug() << "TextManip 2: " << QString((char*)(text));
}


p_Text is "ZEROZEROZEROPC010101". But when I want to print it to VS output with qDebug like;



qDebug() << "TextManip 2: " << QString((char*)(text));


the string is printed to output window as;

"ZEROZEROZEROPC010101?????????"

Any ideas?

Regards

wysota
2nd July 2012, 12:44
Did you null-terminate your string?

high_flyer
2nd July 2012, 12:44
Try to explicitly add a terminating null character '\0' after the last char of your string in the for loop - i.e p_Text[strlen(p_Text)] = '\0';

zgulser
2nd July 2012, 12:57
Hi,

It's a c-string. So it should have a null character at the end right?

high_flyer
2nd July 2012, 13:02
Should and does may differ - as you are manipulating the string.
Besides, you are not allocating a C string, you are allocating a char array - its not the same thing!

Lesiok
2nd July 2012, 13:13
Hi,

It's a c-string. So it should have a null character at the end right?

But You don't copy null character. Look at the condition of the loop execution.

zgulser
2nd July 2012, 13:19
Yeap... That's why I don't understand why ???????? is appended to the end. The null character should be put at the end of c-strings.

high_flyer
2nd July 2012, 13:25
The null character should be put at the end of c-strings.
But you are not allocating a C string!
And we don't know how p_Text is allocated or initialized!

wysota
2nd July 2012, 13:32
Yeap... That's why I don't understand why ???????? is appended to the end.

There is no such thing as a "C string". You have an array of characters that contain textual data. All functions that work on such data expect them to be null terminated and nobody is going to magically discover that if you copy 10 bytes somewhere, you actually want to null-terminate them.


The null character should be put at the end of c-strings.

That's true. And since you didn't put that null character there, you should now correct your error.

zgulser
2nd July 2012, 13:59
Ok..

I corrected by putting '\0' at the end.

However, if I put this,

openssl's




AES_encrypt((unsigned char*)text, (unsigned char*)enc_out, &enc_key);



doesn't work. I mean enc_out returns "". But if I remove '\0' from text, enc_out returns as expected but with ???????? at the end.

Added after 9 minutes:

Ok,

Adding '\0' at the end of enc_out solved the problem.

Thanks for your help.