空字符

空字符Null character)又稱結束符,縮寫NUL,是一個數值為0的控制字符[1][2]。在許多字符编码中都包括空字符,包括ISO/IEC 646ASCII)、C0控制碼通用字符集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;
 i0123456789
 str[i] Wikipedia\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. (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.
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.