의도하지 않은 "가비지"문자 출력

기술노트 96004

아키텍처:

All

컴포넌트:

general

업데이트:

2018-02-28 오전 2:30

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.

죄송하지만, 당사 사이트에서는 Internet Explorer를 지원하지 않습니다.보다 편안한 사이트를 위해 Chrome, Edge, Firefox 등과 같은 최신 브라우저를 사용해 주시길 부탁드립니다.