Sprintf() returning garbage characters

I'm using RTCLib which has functions that returns hour,minute,second in uint8_t.

I used Sprintf to format them to this 00:00:00.

This is the code:

DateTime now = rtc.now();
char str[9];
sprintf(str, "%02u:%02u:%02u", now.hour(),now.minute(),now.second());
str[9] = '\0';

If I print str, the output will look like this:

00:00:00��?u� @���?L��?��?�3 @��?P�?

How do I properly null terminate this char array?

str[9] = '\0';

Your array does not have an element 9.

In any case sprintf() will add the terminating zero

sprintf should take care of it for you - no need to explicitly add a NUL.

I adjusted the size to 8 and remove the manual termination but I'm still getting garbage characters

Edit:
I made the char array global and the garbage characters are gone.

Size needs to be nine and lose the manual termination.

dalvikvm:
I adjusted the size to 8 and remove the manual termination but I'm still getting garbage characters

Edit:
I made the char array global and the garbage characters are gone.

If only you had posted your complete program in the first place ...