More to come...
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
22KB

  1. #ifndef CHAPTER_0_SOURCE // These two, and "#endif" at the end of the file are header guards, we'll talk about them more when the time comes!
  2. #define CHAPTER_0_SOURCE
  3. #include <stdlib.h> // We'll need this header file for malloc, calloc, realloc, free, atexit, rand and exit (some will be used in future chapters).
  4. #include <unistd.h> // And this one for read and write.
  5. #include "chapter_0.h" // We're pasting macros, enumerations and function declarations from header file "chapter_0.h" into this file, at this location.
  6. /*
  7. Function 'in' will perform read system call, literally reading 'size' bytes from standard input, which is terminal in most kernels unless it's redirected to some other file
  8. descriptor, and store it at 'data' memory address, if there's enough space in it. Since this is one of the core functions, if it fails, we want to abort the program and see what
  9. we did wrong... Maybe there wasn't enough space in 'data', maybe 'size' was negative and it overflowed because read system call internally uses 'size_t / unsigned long int', which
  10. is 64 bits wide, maybe we made some other mistake? Just abort, find the error and fix it.
  11. */
  12. void in (void * data, int size) {
  13. fatal_failure (data == NULL, "in: Failed to read from standard input, data is null pointer."); // This function is defined below, but we can call it here.
  14. fatal_failure (size == 0, "in: Failed to read from standard input, size is zero."); // That's because we declared it previously. Look at 'out' function.
  15. (void) read (STDIN_FILENO, data, (unsigned long int) size); // I cast to void type return value of read and write, because I don't really care about it.
  16. }
  17. /*
  18. Similar to 'in' function and read system call, write system call will store 'size' bytes from 'data' memory address into standard output, which is usually what you see in your
  19. terminal. Now, I won't talk much about teletypes, virtual terminals, file descriptor redirections and similar stuff, because I'm not very knowledgable about them. What matters is,
  20. you have a working operating system, terminal and compiler, and you can make things happen. Once you learn C better than me, and start writing your own multi-threaded kernel, core
  21. libraries, compilers and what not, you'll care about those things. I'll briefly talk about function structure for 'reallocate' function soon.
  22. */
  23. void out (void * data, int size) {
  24. fatal_failure (data == NULL, "out: Failed to write to standard output, data is null pointer."); // Notice how we can use function 'fatal_failure' before its' definition.
  25. fatal_failure (size == 0, "out: Failed to write to standard output, size is zero."); // That's because we declared it in 'chapter_0.h' header file.
  26. (void) write (STDOUT_FILENO, data, (unsigned long int) size);
  27. }
  28. /*
  29. Function 'echo' is just a simplification of function 'out', because we'll be using it a lot, notice that it must accept null terminated strings, which are sort of C-style thing. I
  30. really like them, because you don't need to always know size of the string in order to iterate it, but it requires some mental overhead in order to use them without creating hard
  31. to find bugs, which is why newer programming languages consider them unsafe. They're not unsafe, they need to be used like intended.
  32. */
  33. void echo (char * string) {
  34. out (string, string_length (string)); // This function fails when we pass a string that's not null terminated, and we don't care to check for errors...
  35. }
  36. void fatal_failure (int condition, char * message) { // We use this function to abort the program if condition is met and to print the message.
  37. if (condition == TRUE) { // If the variable 'condition' is not equal to 0, we execute the code in curly braces.
  38. echo ("[\033[1;31mExiting\033[0m] "); // Simply printing the message using our 'echo' function, but we also use some colours, more on that later.
  39. echo (message); // Also, notice how "this or that" is implicity 'char *' type... Maybe it's too early to explain it at this point.
  40. echo ("\n"); // This will only print a new line, we'll see how to use it later.
  41. exit (EXIT_FAILURE); // This is the function (and '_exit' system call) that aborts the program with a return code.
  42. } // If condition isn't met, function will just return, and nothing is printed, execution continues.
  43. }
  44. void limit (int * value, int minimum, int maximum) { // This is somewhat similar to limiting a variable to some values, inclusively, we'll use it later.
  45. if ( value == NULL) { return; } // We shouldn't dereference null pointer, but also don't want to abort the program for small mistake.
  46. if (* value <= minimum) { * value = minimum; } // You can also align similar consecutive statements like this, we'll see it more often in switch statement later on...
  47. if (* value >= maximum) { * value = maximum; } // If we pass a null pointer to this function, it won't do anything, just return.
  48. }
  49. /*
  50. Memory management is a whole new topic that's too complex to cover it now in details, and it's the source of most security vunrabilities and hidden bugs. For now, just remember
  51. that every program can read, write or execute only parts of the memory that the kernel allows it. Program can request new memory or release old memory, so some other programs can
  52. use it. We'll learn to use program called Valgrind to find and fix memory related bugs in later chapters. We rely on functions 'calloc', 'realloc' and 'free' from <stdlib.h>
  53. header file, and we'll avoid 'malloc', and use 'realloc' carefully, because they leave new memory uninitialized.
  54. We're internally using function 'calloc' to request new memory, function 'realloc' to enlarge existing memory and function 'free' to release old memory, data that won't be used
  55. later in the program. It's important to "free" all "malloc/calloc/realloc"-ed memory when program finishes successfully, and in some special cases, even when program fails and
  56. aborts. It's important for safety to do so, think of it like open and close braces, if you have some allocations, you should deallocate them later.
  57. Some examples of using them directly (not wrapping them like I like to do) are:
  58. @C
  59. char * data = NULL;
  60. data = malloc (20 * sizeof (* data)); // Allocates 20 bytes of memory for 'data'.
  61. data = calloc (20, sizeof (* data)); // Allocates 20 bytes also, but initializes them to 0 value.
  62. data = realloc (data, 20 * sizeof (* data)); // When 'data' is null pointer, it will be same as 'malloc', else it will reallocate more memory (for correct usage).
  63. // Also, it's best to just use 'calloc', but it complicates some other tasks.
  64. free (data); // Deallocates memory, we'll talk about "double free" later.
  65. @
  66. */
  67. void * allocate (int size) {
  68. char * data = NULL;
  69. data = calloc ((unsigned long int) size, sizeof (* data));
  70. fatal_failure (data == NULL, "standard : allocate : Failed to allocate memory, internal function 'calloc' returned null pointer.");
  71. return ((void *) data);
  72. }
  73. /*
  74. Now, lets see that code formatting in action, with briefly describing function structure in C programming language. Our function is called "reallocate", its' inputs (arguments)
  75. are "data" with type 'void *' (pointer to any type of memory address) and "size" with type 'int' (integer), and its' output is also 'void *' (some memory address). All code
  76. between first '{' and last connected '}' is part of that function. We're using function 'realloc' inside, but we check for error (it return 'NULL' on error), then we print message
  77. and abort the program if there was an error, it there wasn't, we return new enlarged chunk of memory, changing the "data" variable.
  78. */
  79. void * reallocate (void * data, int size) {
  80. data = realloc (data, (unsigned long int) size);
  81. fatal_failure (data == NULL, "standard : reallocate: Failed to reallocate memory, internal function 'realloc' returned null pointer.");
  82. return (data);
  83. }
  84. void * deallocate (void * data) {
  85. if (data != NULL) {
  86. free (data);
  87. }
  88. return (NULL);
  89. }
  90. /*
  91. This program is intended to be a book-like guide for this source code, which is also a book. We'll deal with strings a lot, and they're a good example of code formatting which is
  92. the main topic of chapter zero. In function 'string_length' we have for loop without a body, some people prefer to put '{}' or ';' in same or next line, to express the intention
  93. that the loop shouldn't have a body (code block {}). I just put ';' on the same line. Also, functions 'string_*' could depend on functions 'string_*_limit', but we won't do that
  94. now, and since we've already declared them in header file "chapter_0.h" we can define them and call them in whatever order we want. Nice.
  95. @C
  96. // Simple example of how we could make 'string_*' function dependable on 'string_*_limit' function...
  97. int string_compare (char * string_0, char * string_1) {
  98. return (string_compare_limit (string_0, string_1, string_length (string_0));
  99. }
  100. @
  101. */
  102. int string_length (char * string) {
  103. int length;
  104. fatal_failure (string == NULL, "string_length: String is null pointer."); // If variable 'string' is null pointer, we abort the program.
  105. for (length = 0; string [length] != CHARACTER_NULL; ++length); // In C, strings are null terminated, looping until we see null character is strings' length.
  106. return (length); // If we pass it non-null terminated string, program will fault!
  107. }
  108. /*
  109. Now, I've implemented "unlimited" versions of string comparison, copying and concatenation different from "limited" versions. They correspond with standard library functions
  110. 'strcmp', 'strcpy', 'strcat', 'strncmp', 'strncpy' and 'strncat' found in header file <string.h>. In "unlimited" versions, I rely on the fact that we want to apply the operation
  111. on entire strings, that those strings are null terminated and I used that in my advantage. For example, function 'string_compare' could be something like example below. Also,
  112. notice that 'destination / source' versus 'string_0 / string_1', which do you think is more readable?
  113. @C
  114. int string_compare (char * string_0, char * string_1) {
  115. int offset;
  116. fatal_failure (string_0 == NULL, "string_compare: Destination string is null pointer.");
  117. fatal_failure (string_1 == NULL, "string_compare: Source string is null pointer.");
  118. for (offset = 0; (string_0 [offset] != CHARACTER_NULL) && (string_1 [offset] != CHARACTER_NULL); ++offset) {
  119. if (string_0 [offset] != string_1 [offset]) {
  120. return (FALSE);
  121. }
  122. }
  123. return (TRUE);
  124. }
  125. @
  126. And I used this approach below to show that you can solve the problem using different solutions... You'll notice that "limited" versions have variable 'offset' of type integer. We
  127. use it to interate the strings, while in "unlimited" versions, we iterate on pointers to those strings, which are pushed to the stack. Both versions work, both versions give the
  128. same results, you can use any of them.
  129. */
  130. int string_compare (char * destination, char * source) {
  131. fatal_failure (destination == NULL, "string_compare: Destination string is null pointer."); // This will be seen in next 5 functions too, we don't want NULL here.
  132. fatal_failure (source == NULL, "string_compare: Source string is null pointer.");
  133. for (; (* destination != CHARACTER_NULL) && (* source != CHARACTER_NULL); ++destination, ++source) { // We iterate until either string reaches the null character.
  134. if (* destination != * source) { // In case that characters at the same offset are different:
  135. return (FALSE); // > We return FALSE, 0, since strings aren't the same...
  136. }
  137. }
  138. if (* destination != * source) { // Now, we'll do one last termination check.
  139. return (FALSE);
  140. }
  141. return (TRUE); // Otherwise, strings are same, we return TRUE, 1.
  142. }
  143. char * string_copy (char * destination, char * source) {
  144. char * result = destination; // We need to save pointer to destination string before changing it.
  145. fatal_failure (destination == NULL, "string_copy: Destination string is null pointer.");
  146. fatal_failure (source == NULL, "string_copy: Source string is null pointer.");
  147. for (; * source != CHARACTER_NULL; ++destination, ++source) { // This time and in next function, we iterate only source string.
  148. * destination = * source; // And we assign character at the same offset to destination string (aka copy it).
  149. }
  150. * destination = CHARACTER_NULL; // Copying null termination, since the loop stopped on that condition.
  151. return (result); // Lastly we return the destination string, in order to be able to bind functions.
  152. }
  153. char * string_concatenate (char * destination, char * source) {
  154. char * result = destination;
  155. fatal_failure (destination == NULL, "string_concatenate: Destination string is null pointer.");
  156. fatal_failure (source == NULL, "string_concatenate: Source string is null pointer.");
  157. destination += string_length (destination); // We'll first offset destination string to the end of it.
  158. // Because we want to start copying from the end, aka concatenate it.
  159. for (; * source != CHARACTER_NULL; ++destination, ++source) { // The rest of the function is same as string_copy, so:
  160. * destination = * source; // We could even use it here, but that defies the purpose of learning now.
  161. }
  162. * destination = CHARACTER_NULL; // Again, assign null termination.
  163. return (result);
  164. }
  165. char * string_reverse (char * string) { // Example of implementing "unlimited" version by calling "limited" version.
  166. return (string_reverse_limit (string, string_length (string)));
  167. }
  168. /*
  169. As for "limited" versions of previous 3 functions, they do the same thing, but are capped to some variable 'limit'. These functions have their own use-case, for example, if
  170. strings aren't null terminated, if you're not sure that they are null terminated, if we're dealing with binary (not textual) data (casted to char *), and many more cases. I won't
  171. write comments for 'string_copy_limit', 'string_concatenate_limit' and 'string_reverse_limit', try to read them and understand what kind of operation they'll perform with your
  172. current knowledge of C language.
  173. */
  174. int string_compare_limit (char * destination, char * source, int limit) {
  175. int offset;
  176. fatal_failure (destination == NULL, "string_compare_limit: Destination string is null pointer."); // This is the new trend, check for unimportant things.
  177. fatal_failure (source == NULL, "string_compare_limit: Source string is null pointer."); // At least this isn't too verbose. I hope...
  178. for (offset = 0; offset < limit; ++offset) { // Now, we'll iterate until 'limit' is reached, but it can overrun.
  179. if (destination [offset] != source [offset]) { // All said here applies to next two functions as well...
  180. return (FALSE); // As soon as 2 characters mismatch, they're not same, we return FALSE.
  181. }
  182. }
  183. return (TRUE); // Otherwise, we're reached the end, they're same, we return TRUE.
  184. }
  185. char * string_copy_limit (char * destination, char * source, int limit) {
  186. int offset;
  187. fatal_failure (destination == NULL, "string_copy_limit: Destination string is null pointer.");
  188. if ((limit <= 0) || (source == NULL)) {
  189. return (destination);
  190. }
  191. for (offset = 0; offset < limit; ++offset) {
  192. destination [offset] = source [offset];
  193. }
  194. return (destination);
  195. }
  196. char * string_concatenate_limit (char * destination, char * source, int limit) {
  197. int offset, destination_length, source_length;
  198. fatal_failure (destination == NULL, "string_concatenate_limit: Destination string is null pointer.");
  199. if ((limit <= 0) || (source == NULL)) {
  200. return (destination);
  201. }
  202. destination_length = string_length (destination);
  203. source_length = string_length (source);
  204. for (offset = 0; (offset < source_length) && (offset < limit); ++offset) {
  205. destination [destination_length + offset] = source [offset];
  206. }
  207. return (destination);
  208. }
  209. char * string_reverse_limit (char * string, int limit) {
  210. int i;
  211. fatal_failure (string == NULL, "string_reverse: String is null pointer.");
  212. for (i = 0; i < limit / 2; ++i) {
  213. char temporary = string [i];
  214. string [i] = string [limit - 1 - i];
  215. string [limit - 1 - i] = temporary;
  216. }
  217. return (string);
  218. }
  219. /*
  220. We'll use this function in many other chapters (in other C source files!), but we'll be careful, since compiler can't catch all the mistakes we make. Lets listen a story!
  221. Compiler likes you because you are his master. You tell him what to do (with passing flags as 'argv'), you give him the tool (your text files) and he'll do it. Sometimes he can
  222. complain, like "you gave me a shovel to chop some firewood" or "you gave me an axe to clean the leaves from the road", and he can't do that task. But if you give him a proper tool
  223. for proper task, he'll do it and won't complain at all. However, sometimes, you give him an imperfect tool (your C program full of subtle bugs) and he won't notice it. He'll do
  224. the job (translate bunch of ASCII characters into bunch of bytes), and say he's finished. Then you go out and see the results (run your executable), and it's all mess! You're like
  225. "What the hell, do as I say!", but he doesn't know what he did wrong... And in fact, it was your fault for giving him a imperfect tool all along. That's why we sometimes need more
  226. difficult to use servants. When you, as his master, tell him to do some job for you, he'll complain endlessly. You should use all your servants appropriately, each of them for
  227. different kind of task, and you'll learn to choose them wisely.
  228. Now, funny story aside, some languages are considered safe because they won't compile your code if they find any kind of syntax mistake. Ada is very strict programming language,
  229. we'll talk about it in later chapters, as Ada compilers complain a lot about the source code, but they can't validate incorrect algorythm. Pust is also very strict language, but
  230. it sucks, and it's unreadable pile of characters. Remember, no matter how strict language you use, it'll never validate correctness of the algorythm, only syntax mistakes and
  231. few other checks like life-times, bounds, etc. I'll mention this a lot, think twice, write once.
  232. Obedient servants:
  233. $ gcc -Wall
  234. $ clang -Wall
  235. Complicated servants:
  236. $ gcc -ansi -Werror -Wall -Wextra -Wpedantic
  237. $ clang -ansi -Werror -Weverything
  238. Terrible servants (same as above, but with also using):
  239. $ splint [custom flags]
  240. $ valgrind --show-leak-kinds=all --leak-check=full
  241. */
  242. char * string_realign (char * string, int amount, char character) { // Now, this is our "align string to right" function, lets explain it.
  243. int offset, length; // We're declaring two local (automatic) variables of type 'int'.
  244. length = string_length (string); // We'll use variable 'length' later in the code, so we initialize it to length of the string.
  245. for (offset = 0; offset != length; ++offset) { // We're essentially moving the string to the right, iterating through its' length to amount.
  246. string [amount - offset - 1] = string [length - offset - 1]; // Needless to say, string needs to have enough memory ((pre) allocated) for it to store it.
  247. }
  248. for (offset = 0; offset != amount - length; ++offset) { // Now, we have some "garbage" data left from the actual string, so we iterate through left side and:
  249. string [offset] = character; // Assign to it argument 'character' that we provided in a function call. We can align with anything.
  250. }
  251. string [amount] = CHARACTER_NULL; // I like to null terminate them explicitly, so I don't have to worry about tiny bugs later.
  252. return (string); // Lastly, we return a pointer to our modified string, in order to, again, bind function calls.
  253. }
  254. /*
  255. Ignore what next two functions do, it's about memory stuff that we'll cover in later chapters.
  256. */
  257. int memory_compare (void * destination, void * source, int length) {
  258. int offset;
  259. char * cast_0 = (char *) destination;
  260. char * cast_1 = (char *) source;
  261. fatal_failure (destination == NULL, "memory_compare: Memory is null pointer.");
  262. if (source == NULL) {
  263. return (FALSE);
  264. }
  265. for (offset = 0; offset != length; ++offset) {
  266. if (cast_0 [offset] != cast_1 [offset]) {
  267. return (FALSE);
  268. }
  269. }
  270. return (TRUE);
  271. }
  272. void memory_copy (void * destination, void * source, int length) {
  273. int offset;
  274. char * cast_0 = (char *) destination;
  275. char * cast_1 = (char *) source;
  276. fatal_failure (destination == NULL, "memory_copy: Memory is null pointer.");
  277. if (source == NULL) {
  278. return;
  279. }
  280. for (offset = 0; offset != length; ++offset) {
  281. cast_0 [offset] = cast_1 [offset];
  282. }
  283. }
  284. /*
  285. Again, please consider these 'terminal_*' functions some form of black magic... For now, just take a look at how I format the code in them.
  286. */
  287. void terminal_clear (void) {
  288. echo ("\033[2J\033[H");
  289. }
  290. void terminal_colour (int colour, int effect) {
  291. char format [8] = "\033[ ;3 m";
  292. format [2] = (char) (effect % EFFECT_COUNT) + '0';
  293. format [5] = (char) (colour % COLOUR_COUNT) + '0';
  294. echo (format);
  295. }
  296. void terminal_cancel (void) {
  297. echo ("\033[0m");
  298. }
  299. void terminal_show_cursor (int show) {
  300. if (show != 0) {
  301. echo ("\033[?25h");
  302. } else {
  303. echo ("\033[?25l");
  304. }
  305. }
  306. #endif