Null Character: Difference between revisions

[unchecked revision][unchecked revision]
Content deleted Content added
No edit summary
m Bot: Replace deprecated source tag with syntaxhighlight
 
(2 intermediate revisions by 2 users not shown)
Line 9:
== How to use and detect a null terminator ==
In C, the null terminator is automatically attached at the end of a string when you create it with double quotation marks ("Hello, OSDev!" is an array of 14 characters, as after the '!', there is a '\0' or null byte). The standard library uses this to detect the length of strings and operate consequentially with them, but behind the header files, the code that detects the null terminator is quite easy but important to understand.
<sourcesyntaxhighlight lang="c">
size_t strlen(const char *str)
{
Line 21:
}
 
</syntaxhighlight>
</source>
This C code is a quick-and-easy implementation of the strlen() standard function. All it does is increment "n" while the n-th character of the string "str" is not a null terminator, and then return it. If no null byte is found in the string, the function may overflow. Problably it will find one null byte somewhere, but if not, it will read from an invalid address, generating an exception. Keep in mind that detecting a null terminator is only usefull in the context of strings, as memory in general can have arbitrary zeros that don't mean the end of its contents.
 
Line 28:
In most of the dialects of assembly, strings variables (or more accurrately, labels) can be defined to be null terminated when created. Some assemblers accept the tag ".asciiz" followed by an string between double quotation marks to create (unsually in the data section) a string, that then you can treat as a normal C-like string.
Example under 64 bit Intel assembly, with NASM:
<sourcesyntaxhighlight lang="asm">
bits 64
 
Line 45:
xor rax, rax
call printf
</syntaxhighlight>
</source>
As printf will start reading the characters to print from address "str" until a NULL, the output of the program will be:
<pre>
Line 51:
</pre>
== OS desing considerations ==
String-related functions are crutialcrucial, you should implement them in your standard library,. soSo keep in mind that null terminator detection is indispensable. IsIt notis usually not a good idea to specify the length of ana string via a number variable, but it is not a bad practice to specify a maximunmaximum length in some contexts (maybe because you can't dinamicallydynamically allocate memory for a string, so you just declasedeclare something like "char str[MAX_STR]").
 
--[[User:Virtualexception|Virtualexception]] 14:56, 11 March 2024 (CDT)
== See also ==
=== External Links ===
Line 58:
* [https://elixir.bootlin.com/glibc/glibc-2.17/source/string/strlen.c GLibc's strlen() source]
* [https://p403n1x87.github.io/getting-started-with-x86-64-assembly-on-linux.html x64 Intel assembly basics]
 
 
--[[User:Virtualexception|Virtualexception]] 14:5658, 11 March 2024 (CDT)