Unexplained "garbage" characters in strings

Technical Note 96004

Arkitekturer:

All

Komponent:

general

Uppdaterad:

2015-11-06 13:52

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.

Det här innehållet finns tyvärr inte på svenska.

Vår webbplats finns främst på vårt koncernspråk engelska, förutom det innehåll för investerare som vi är lagstadgade att kommunicera på svenska. Vi rekommenderar att du besöker vår globala webbplats på engelska för att få en bättre upplevelse.

Vi stöder inte längre Internet Explorer. För att få bästa möjliga upplevelse av iar.com rekommenderar vi att du uppgraderar till en modern webbläsare som Chrome eller Edge.