Unexplained "garbage" characters in strings

Technical Note 96004

Architectures:

All

Component:

general

Updated:

11/6/2015 1:52 PM

Introduction

In some cases, there are unexplained "garbage" characters in strings printed with printf or after using sprintf.

Solution

Check the format strings used in sprintf/printf thoroughly.
Also check for faulty strncat usage (example below).

Background

There are a number of explanations for the unexplained characters:

  1. 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).
  2. 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.
  3. The number of arguments to "sprintf" does not match the format string. Consider the following example:
    const char *formatstr = "Test1 %c Test2 %c\n";
    printf(formatstr, 'A');

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.

We do no longer support Internet Explorer. To get the best experience of iar.com, we recommend upgrading to a modern browser such as Chrome or Edge.