空字符

本页使用了标题或全文手工转换
维基百科,自由的百科全书

空字符Null character)又称结束符,缩写NUL,是一个数值为0的控制字符[1][2]。在许多字符编码中都包括空字符,包括ISO/IEC 646ASCII)、C0控制码英语C0 and C1 control codes通用字符集UnicodeEBCDIC等,几乎所有主流的程式语言都包括有空字符[3]

这个字符原来的意思类似NOP指令,当送到列表机终端机时,设备不需作任何的动作(不过有些设备会错误的列印或显示一个空白)。

空字符在C语言及其衍生语言及许多资料型态中都非常的重要,在C语言中空字符是字串的结束码[4],这样的字串称为空字符终止字串或ASCIIZ字串[5]。因此字串的长度可以为任意自然数,但需多增加一个字元的空间储存空字元。

表示方式

在程式源代码的字串或字元常数中,常用转义序列\0表示空字符[6]。在C语言及其衍生语言中,\0不是一个单独的转义序列,而是一个以八进位表示常数,而常数的数值为0,\0后面不能接0至7的数字,不然会视为是一个八进位的数字。其他语言表示空字符的方式包括\000\x00Unicode表示法的\u0000或是\z。在URL中可以用%00表示空字符,若是配合不正确的输入验证,会造成一个称为“空字符注入”(null byte injection)的计算机安全隐患,可能会导致安全性的问题[7]

有时在文件中会用一个其中有NUL字元,大小和一般英文字母同宽的符号来表示空字符。在Unicode中有一个字元是对应空字符的视觉表示方式,即“NUL符号”U+2400 (),但在Unicode中真正的空字符是U+0000。

程式语言会自动在字串结尾加上结束符,不需由程式员自己打上去。

例如以下的C++代码:

char str[] = "Wikipedia";
cout << str << endl;
 i 0 1 2 3 4 5 6 7 8 9
 str[i]  W i k i p e d i a \0

9个字符加上结束符,该字串的长度是10。当程式员使用 cout 打印字串到显示屏,C++程式便由 str 第0格开始,一直打印到结束符。当然,结束符本身并不会列印。

相关条目

参考资料

  1. ^ ASCII format for Network Interchange: sec. 5.2. RFC 20. NUL (Null): The all-zeros character which may serve to accomplish time fill and media fill. 
  2. ^ The set of control characters of the ISO 646 (PDF). Secretariat ISO/TC 97/SC 2: 4.4. 1975-12-01 [2012-08-15]. (原始内容 (PDF)存档于2012-07-29). Position: 0/0, Name: Null, Abbreviation: Nul 
  3. ^ "A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string literal." — ANSI/ISO 9899:1990 (the ANSI C standard), section 5.2.1
  4. ^ "A string is a contiguous sequence of characters terminated by and including the first null character" — ANSI/ISO 9899:1990 (the ANSI C standard), section 7.1.1
  5. ^ "A null-terminated byte string, or NTBS, is a character sequence whose highest-addressed element with defined content has the value zero (the terminating null character)" — ISO/IEC 14882 (the ISO C++ standard), section 17.3.2.1.3.1
  6. ^ Kernighan and Ritchie, C, p. 38
  7. ^ Null Byte Injection页面存档备份,存于互联网档案馆) WASC Threat Classification Null Byte Attack section.