Sijith
Sijith

Reputation: 3932

How to concat integer with wchar_t

I want to concat an integer with wchar_t, tried below method but its crashing

const wchar_t mySalvo[10] = L"Group:";  // THis is global
int salvo = 0;  
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1);
wcscat(mySalvo, buffer);  // app crashes here

ITs in C

Upvotes: 0

Views: 411

Answers (2)

gavinb
gavinb

Reputation: 20028

There are numerous issues with this code:

const wchar_t mySalvo[10] = L"Group:";  // THis is global
int salvo = 0;  
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1);
wcscat(mySalvo, buffer);  // app crashes here
  • First of all, using a global is not best practice. There doesn't appear to be any good reason for it to be global, so just make it local to where you need it.
  • Second, you've specified it is a constant string, and initialised it to a string literal, which means it will probably be stored in a read-only segment of memory. Yet you're writing into it with wcscat (your compiler surely gave you a warning??).
  • Also the string is limited to 10 wchar_t elements, so even if it weren't read-only, it would only be long enough to store a 3 digit number.
  • the buffer intended to store your converted string is one wide character long (and the initialisation to newline is pointless) so you will overflow your buffer with any value of salvo above 9.
  • the third parameter to itoa is the number base, which would normally be 10. It is meaningless to have a number of base 1.
  • you're using wcscat to write into a constant string, which is verboten, even assuming it were long enough.

So there's a lot of fundamentals here you need to come to terms with. String allocation, memory initialisation, arrays, constant variables and constant literals, and more.

What you are trying to do is simply produce a formatted string. The sprintf family of string formatting functions provide all you could possibly need, plus a secure way of doing it.

The simplest solution would be something like this:

void show_message(unsigned salvo)
{
    wchar_t message[64];
    swprintf_s(message, sizeof(message), L"Group: %u\n", salvo);

    // do something with message!
}

So if you called show_message(123), the resulting value in message would be: "Group: 123\n".

Upvotes: 1

0___________
0___________

Reputation: 67556

mySalvo is const - which was spotted by Chris.

And on top of it

wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1); -
wcscat(mySalvo, buffer);  // app crashes here

it is undefined behavior asd you do not have enough space to accommodate L"\n". Both calls invoke the UB. itoa will not work with the wchar_t strings. You need to find the appropriate function.

try wchar_t buffer[2] = L"\n"; instead

Upvotes: 0

Related Questions