Unexplained "garbage" characters in strings
Technical Note 96004
In some cases, there are unexplained "garbage" characters in strings printed with printf or after using sprintf.
Check the format strings used in sprintf/printf thoroughly.
Also check for faulty strncat usage (example below).
There are a number of explanations for the unexplained characters:
- Some of the strings used by %s are not terminated by the null '\0' character. This could be the case if "strncpy" has been used earlier (strncpy does not always terminate the destination string with a null character).
- The null character may be missing if a %s is mixed up with a %d, for example, printf("%s", 2000) will print anything that is located at address 0x7D0.
- The number of arguments to "sprintf" does not match the format string. Consider the following example:
const char *formatstr = "Test1 %c Test2 %c\n";
The number of arguments to the printf (or sprintf) function does not match the format string (too few). Since the format string is dynamic, the compiler does not issue any warning. In this example, depending on what is inside the memory, the following is printed: "Test1 A Test2 @".
A technique to see if you are looking at uninitialised, random memory is to fill RAM with a pattern, for example '0xAA'. If the garbage characters change to '0xAA', then you know that there is a string handling error somewhere in your application. (If not, the character may come from some other data or code location).
Another technique is to initialise any destination strings completely with '\0' before using them. Note that this should be done just as a test - it might make the symptom go away, but the problem is still there.
All product names are trademarks or registered trademarks of their respective owners.