Ағылшыншамен салыстырыңыз: абзацты басыңыз — түпнұсқа терезеде ашылады. Абзац астындағы EN түймесі оны мәтін ішінде көрсетеді.
Мазмұны
Кіріспе
Деректер құрылымы
Data structure
Компьютерлік бағдарламалауда, нөлмен аяқталатын жол – бұл таңбалардан тұратын массив ретінде сақталатын және нөлдік таңбамен (осы мақалада "NUL" деп аталатын, ішкі мәні нөлге тең таңба, нөлдік символмен шатастырылмау керек) аяқталатын таңба тізбегі. Балама атаулары – C жолы, C бағдарламалау тіліне сілтеме жасайды және ASCIIZ (бірақ C ASCII-ден басқа кодировкаларды да қолдана алады). Жолдың ұзындығы (бірінші) NUL іздеу арқылы анықталады. Бұл жол ұзындығына байланысты O(n) (сызықтық уақыт) уақытын қажет ететіндіктен, баяу болуы мүмкін. Сондай-ақ, жолдың ішінде NUL таңбасы болмайды (жадта NUL бар, бірақ ол соңғы таңбадан кейін орналасқан, жолдың өзінде емес).
In computer programming, a null terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with an internal value of zero, called "NUL" in this article, not same as the glyph zero). Alternative names are C string, which refers to the C programming language and ASCIIZ (although C can use encodings other than ASCII). The length of a string is found by searching for the (first) NUL. This can be slow as it takes O(n) (linear time) with respect to the string length. It also means that a string cannot contain a NUL (there is a NUL in memory, but it is after the last character, not in the string).
Тарих
Нөлдік аяқталатын тізбектер PDP 11 құрастыру тілдерінің ASCIZ директивасымен және PDP 10 үшін MACRO 10 макро құрастыру тілінің ASCIZ директивасымен жасалды. Бұл C бағдарламалау тілінің дамуына дейін пайда болған, бірақ басқа да тізбектер жиі қолданылды. C (және одан туындаған тілдер) дамытылған кезде жад өте шектеулі болғандықтан, тізбектің ұзындығын сақтау үшін тек бір байтты пайдалану тартымды болды. Сол кездегі жалғыз танымал балама, көбінесе "Паскаль тізбегі" деп аталатын (қазіргі заманғы термині "ұзындығы префикстелген"), тізбектің ұзындығын сақтау үшін алдыңғы байтты қолданды. Бұл тізбекте NUL символын пайдалануға мүмкіндік берді және ұзындығын табу үшін тек бір жадқа қол жеткізу қажет болды (O(1) (тұрақты) уақыт), бірақ тізбектің ұзындығы 255 символмен шектелді. C тілінің авторы Деннис Ричи, тізбектің ұзындығына шектеу қоймау және оның тәжірибесінде санауды сақтау, терминаторды пайдаланудан гөрі ыңғайсыз болғандықтан, нөлдік аяқталу әдісін таңдады. Бұл процессордың нұсқаулар жиынтығының дизайнына әсер етті. 1970 және 1980 жылдары Zilog Z80 және DEC VAX сияқты кейбір процессорларда ұзындығы префикстелген тізбектерді өңдеуге арналған арнайы нұсқаулар болды. Дегенмен, нөлдік аяқталатын тізбектер кеңінен таралған сайын, CPU дизайнерлері оны ескеруді бастады, мысалы, IBM-нің 1992 жылы ES/9000 520-ға "Логикалық тізбекке көмек" нұсқауларын және 2015 жылы IBM z13-ке векторлық тізбек нұсқауларын қосу шешімінде көрінеді. FreeBSD әзірлеушісі Poul Henning Kamp, ACM Queue журналында жазғанда, 2 байттық (бір байт емес) ұзындықты жеңген нөлдік аяқталатын тізбектерді "ең қымбат бір байттық қате" деп атады.
Null terminated strings were produced by the ASCIZ directive of the PDP 11 assembly languages and the ASCIZ directive of the MACRO 10 macro assembly language for the PDP 10. These predate the development of the C programming language, but other forms of strings were often used. At the time C (and the languages that it was derived from) was developed, memory was extremely limited, so using only one byte of overhead to store the length of a string was attractive. The only popular alternative at that time, usually called a "Pascal string" (a more modern term is "length prefixed"), used a leading byte to store the length of the string. This allows the string to contain NUL and made finding the length need only one memory access (O(1) (constant) time), but limited string length to 255 characters. C designer Dennis Ritchie chose to follow the convention of null termination to avoid the limitation on the length of a string and because maintaining the count seemed, in his experience, less convenient than using a terminator. This had some influence on CPU instruction set design. Some CPUs in the 1970s and 1980s, such as the Zilog Z80 and the DEC VAX, had dedicated instructions for handling length prefixed strings. However, as the null terminated string gained traction, CPU designers began to take it into account, as seen for example in IBM's decision to add the "Logical String Assist" instructions to the ES/9000 520 in 1992 and the vector string instructions to the IBM z13 in 2015. FreeBSD developer Poul Henning Kamp, writing in ACM Queue, referred to the victory of null terminated strings over a 2 byte (not one byte) length as "the most expensive one byte mistake" ever.
Шектеулер
Бұл бейнелеуді іске асыру оңай болғанымен, ол қателерге және өнімділік мәселелеріне бейім. Нөлдік соқтыру тарихи түрде қауіпсіздік проблемаларын тудырды. Сызықтың ортасына енгізілген NUL оны күтпеген жерде тоқтатады. Көбінесе кездесетін қате – NUL үшін қосымша орынды бөлуді ұмыту, нәтижесінде ол жақын жадқа жазылып, бұзады. Тағы бір мәселе – NUL-ді жазуды мүлдем жіберіп алу, бұл сынақ кезінде көрінбейтін, себебі жад блогында бұрыннан нөлдер болған. Ұзындығын анықтаудың қиындығынан көптеген бағдарламалар, сызықты белгілі өлшемдегі буферге көшіргенде, оның ұзындығын тексермейтін, егер сызық тым ұзын болса, буфердің толып кетуіне себеп болатын. Нөлді сақтау мүмкін болмағандықтан, мәтіндік және екілік деректерді бөлек сақтау және оларды әртүрлі функциялармен өңдеу қажет (екіншісі деректердің ұзындығын да талап етеді). Бұл кодтың қайталануына және дұрыс емес функция қолданылғанда қателерге әкелуі мүмкін. Ұзындықты анықтау жылдамдығының мәселесін strlcpy сияқты O(n) болатын басқа операциямен біріктіру арқылы шешуге болады. Дегенмен, бұл әрқашан түсінікті API-ге әкелмейді.
While simple to implement, this representation has been prone to errors and performance problems. Null termination has historically created security problems. A NUL inserted into the middle of a string will truncate it unexpectedly. A common bug was to not allocate the additional space for the NUL, so it was written over adjacent memory. Another was to not write the NUL at all, which was often not detected during testing because the block of memory already contained zeros. Due to the expense of finding the length, many programs did not bother before copying a string to a fixed size buffer, causing a buffer overflow if it was too long. The inability to store a zero requires that text and binary data be kept distinct and handled by different functions (with the latter requiring the length of the data to also be supplied). This can lead to code redundancy and errors when the wrong function is used. The speed problems with finding the length can usually be mitigated by combining it with another operation that is O(n) anyway, such as in strlcpy. However, this does not always result in an intuitive API.
Таңба кодтамалары
Нөлдік аяқталатын тізбектер кодтаудың кез келген жерінде нөлдік байтты (0x00) пайдаланбауын қажет етеді; сондықтан барлық мүмкін ASCII немесе UTF-8 тізбектерін сақтау мүмкін емес. Дегенмен, ASCII немесе UTF-8 тізбектерінің NUL таңбасынан басқа барлық таңбаларын нөлдік аяқталатын тізбектерде сақтау жиі кездеседі. Кейбір жүйелер "өзгертілген UTF-8" қолданады, ол NUL-ді екі нөлдік емес байт ретінде (0xC0, 0x80) кодтайды, осылайша барлық мүмкін тізбектерді сақтауға мүмкіндік береді. Бұл UTF-8 стандартында рұқсат етілмейді, себебі бұл артық ұзын кодтау болып есептеледі және қауіпсіздік қаупін тудырады. Тізбектің соңы ретінде UTF-8-де қолданылмайтын 0xFE немесе 0xFF сияқты басқа байттарды да пайдалануға болады. UTF-16 2 байттық бүтін сандарды қолданады және кез келген байты нөл болуы мүмкін (әсіресе ASCII мәтінін көрсету кезінде әрбір екінші байт нөл болады), сондықтан оны нөлдік аяқталатын байт тізбегінде сақтауға болмайды. Алайда, кейбір бағдарламалау тілдері 16 биттік UTF-16 таңбалар тізбегін, 16 биттік NUL (0x0000) арқылы аяқталатын күйде жүзеге асырады.
Null terminated strings require that the encoding does not use a zero byte (0x00) anywhere; therefore it is not possible to store every possible ASCII or UTF 8 string. However, it is common to store the subset of ASCII or UTF 8 – every character except NUL – in null terminated strings. Some systems use "modified UTF 8" which encodes NUL as two non zero bytes (0xC0, 0x80) and thus allow all possible strings to be stored. This is not allowed by the UTF 8 standard, because it is an overlong encoding, and it is seen as a security risk. Some other byte may be used as end of string instead, like 0xFE or 0xFF, which are not used in UTF 8. UTF 16 uses 2 byte integers and as either byte may be zero (and in fact every other byte is, when representing ASCII text), cannot be stored in a null terminated byte string. However, some languages implement a string of 16 bit UTF 16 characters, terminated by a 16 bit NUL (0x0000).
Жағдайдың жақсаруы
C тізбектерін басқаруды қателерге осалдығын азайту үшін көптеген әрекеттер жасалды. Бір стратегия – strdup және strlcpy сияқты қауіпсіз функцияларды қосу, ал gets сияқты қауіпсіз емес функцияларды қолданудан бас тарту. Тағы бір тәсіл – C тізбектерін объектіге бағытталған қаптамаға орау, осылайша тек қауіпсіз шақырулар жасалуын қамтамасыз ету. Дегенмен, қауіпсіз емес функцияларды шақыруға мүмкіндік бар. Көптеген қазіргі заманғы кітапханалар C тізбектерін 32 бит немесе одан да үлкен ұзындық мәнін қамтитын құрылыммен алмастырады (бұл ұзындығы алдынан қосылатын тізбектер үшін ескерілгеннен әлдеқайда көп), сондай-ақ көбінесе тағы бір көрсеткіш, сілтеме саны және тіпті NUL символын қосып, C тізбегіне қайта түрлендіруді жеделдетуге мүмкіндік береді. Жады қазір әлдеқайда үлкен, сондықтан егер әр тізбекке 3 (немесе 16 немесе одан да көп) байт қосу нақты проблема тудырса, бағдарламалық құрал көптеген кішкентай тізбектермен жұмыс істеуі керек болады, сондықтан басқа сақтау әдісі одан да көп жадты үнемдеуі мүмкін (мысалы, көптеген дубликаттар болған жағдайда хэш-кесте жадты тиімдірек пайдалануы мүмкін). Мысалдарға C++ стандартты үлгілер кітапханасы std::string, Qt QString, MFC CString, Core Foundation-нан C-ге негізделген CFString және оның Objective C әріптесі Foundation-нан NSString, екеуі де Apple компаниясына тиесілі. Сондай-ақ, жіптерді сақтау үшін арқан сияқты күрделі құрылымдар қолданылуы мүмкін.
Many attempts to make C string handling less error prone have been made. One strategy is to add safer functions such as strdup and strlcpy, whilst deprecating the use of unsafe functions such as gets. Another is to add an object oriented wrapper around C strings so that only safe calls can be done. However, it is possible to call the unsafe functions anyway. Most modern libraries replace C strings with a structure containing a 32 bit or larger length value (far more than were ever considered for length prefixed strings), and often add another pointer, a reference count, and even a NUL to speed up conversion back to a C string. Memory is far larger now, such that if the addition of 3 (or 16, or more) bytes to each string is a real problem the software will have to be dealing with so many small strings that some other storage method will save even more memory (for instance there may be so many duplicates that a hash table will use less memory). Examples include the C++ Standard Template Library std::string, the Qt QString, the MFC CString, and the C based implementation CFString from Core Foundation as well as its Objective C sibling NSString from Foundation, both by Apple. More complex structures may also be used to store strings such as the rope.