yohhoyの日記

技術的メモをしていきたい日記

文字列リテラル最大長の最低保証

C/C++言語における文字列リテラル(string literal)最大長に対する最低保証について。C言語では文字列長さに関する制約が存在する。*1

要約:

  • C90:509文字までは言語仕様にて保証。それ以上は環境限界に従う。
    • 509 = 512バイト − CRLF改行(2) − NUL終端(1)
  • C99以降:4095文字までは言語仕様にて保証。それ以上は環境限界に従う。
  • C++:文字列リテラル長に関する上限値なし。

gccでは同制約について警告するオプション -Woverlength-strings が存在する。同オプションは -Wpedantic オプション指定に含まれる。

-Woverlength-strings
Warn about string constants that are longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants that are much longer than the standard's minimum limit, but very portable programs should avoid using longer strings.

The limit applies after string constant concatenation, and does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.

This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.

https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

C90

C90 2.2.4.1より引用。

The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:

  • (snip)
  • 509 characters in a character string literal or wide string literal (after concatenation)
  • (snip)

C99

C99 5.2.4.1より引用。

The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:

  • (snip)
  • 4095 characters in a character string literal or wide string literal (after concatenation)
  • (snip)

*1:ISO/IEC 9899における"Environmental limits"の対訳として、JIS X 3010では"環境限界"を用いている。本文中でも同訳語にならう。