Search code examples
cstringstrcatitoa

Problem with concatenation + itoa


I have the following code:

char stringHour[50], stringMinute[50], stringSecond[50];

// lots of code...
itoa(hour, stringHour, 10);
itoa(minute, stringMinute, 10);
itoa(second, stringSecond, 10);

strcat(":", stringSecond);
strcat(":", stringMinute);
strcat(stringMinute, stringSecond);
// stringHour contains both HH and :SS:MM
strcat(stringHour, stringMinute);
drawText(HRES/2 - 4, VRES - GLYPH_HEIGHT*2, 
stringHour, black);

hour, minute and second are all ints.

What I want to do is diplay time as follows: HH:MM:SS.

The variables are guaranteed to be between 0 and 59 (except hout, 0-24).

drawText is correct.

This block of code crashes my program, and I can't find anything wrong with it. Can you?

Thanks for your time!


Solution

  • More than likely the bit that is failing is this piece:

    ... stuff removed
    strcat (":", 
    ... other stuff removed
    

    You almost certainly can't strcat stuff onto a string literal on the platform you are using.

    The strcat approach has buffer overflow safety issues as well. Maybe using snprintf might be a better alternative?