空字元

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書

空字元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.