{"id":15030896,"url":"https://github.com/agavrel/42_cheatsheet","last_synced_at":"2025-04-05T21:10:30.959Z","repository":{"id":37401426,"uuid":"202980654","full_name":"agavrel/42_CheatSheet","owner":"agavrel","description":"A comprehensive guide to 50 years of evolution of strict C programming, a tribute to Dennis Ritchie's language","archived":false,"fork":false,"pushed_at":"2023-07-28T14:25:42.000Z","size":2443,"stargazers_count":1764,"open_issues_count":2,"forks_count":145,"subscribers_count":34,"default_branch":"master","last_synced_at":"2025-03-29T20:08:33.279Z","etag":null,"topics":["42","42born2code","42fremont","42madrid","42paris","42school","42seoul","42tokyo","bitwise","learning","school","sdl2","simd"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/agavrel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2019-08-18T08:52:46.000Z","updated_at":"2025-03-29T18:30:36.000Z","dependencies_parsed_at":"2024-04-02T12:54:48.731Z","dependency_job_id":null,"html_url":"https://github.com/agavrel/42_CheatSheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agavrel%2F42_CheatSheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agavrel%2F42_CheatSheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agavrel%2F42_CheatSheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/agavrel%2F42_CheatSheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/agavrel","download_url":"https://codeload.github.com/agavrel/42_CheatSheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247399885,"owners_count":20932880,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["42","42born2code","42fremont","42madrid","42paris","42school","42seoul","42tokyo","bitwise","learning","school","sdl2","simd"],"created_at":"2024-09-24T20:14:28.267Z","updated_at":"2025-04-05T21:10:30.933Z","avatar_url":"https://github.com/agavrel.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 42 School Cheat Sheet by [agavrel](https://www.github.com/agavrel)\n\n## :two_hearts: Intended for 42 alumni, current students and candidates\n\n\u003e **Truth can only be found in one place: the code** – *Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship*\n\nA comprehensive guide to 50 years of evolution of strict C programming, a tribute to Dennis Ritchie's language\n\n---\n# Table of Content\n\n* **[0. About 42 School](#about-42-school)**\n    * **[0x00 ~ What is 42 School](#0x00--what-is-42-school)**\n    * **[0x01 ~ For Candidates: About the \"Piscine\"](#0x01--for-candidates-about-the-piscine)**    \n        * **[My guess on the success criteria](#coffee-my-guess-on-the-success-criteria)**  \n        * **[List of Essential Items](#star-list-of-essential-items)**  \n    * **[0x02 ~ Coding simple C programs](#0x02--coding-simple-c-programs)**  \n        * **[First by installing a C compiler on your computer](#first-by-installing-a-c-compiler-on-your-computer)**  \n\t\t* **[C Data Types](#c-data-types)**  \n\t\t* **[Pointers](#pointers)**  \n        * **[ft_putchar](#ft_putchar)**  \n        * **[ft_strlen](#ft_strlen)**  \n        * **[ft_putstr](#ft_putstr)**  \n    * **[0x03 ~ 42 Projects Guides](#0x03--42-projects-guides)**  \n    * **[0x04 ~ Choosing your Path](#0x04--choosing-your-path)**  \n    * **[0x05 ~ Swindle the norminette - *truander la norme*](#0x05--swindle-the-norminette---truander-la-norme)**  \n        * **[While Loops](#while-loops)**  \n        * **[If Brackets](#if-brackets)**  \n        * **[Write Colorful Usage](#write-colorful-usage)**  \n        * **[Function Pointers](#function-pointers)**  \n\t* **[0x06 ~ Impossible is not C](#0x06--impossible-is-not-c)**  \n\n---\n* **[1. Common Beginner Mistakes](#fire-common-beginner-mistakes)**  \n    * **[0x00 ~ Array Overflow](#0x00--array-overflow)**  \n    * **[0x01 ~ Segmentation Fault](#0x01--segmentation-fault)**  \n    * **[0x02 ~ Bus error](#0x02--bus-error)**  \n    * **[0x03 ~ Stack smashing](#0x03--stack-smashing)**  \n    * **[0x04 ~ Modifying value of a local variable given as function parameter](#0x04--modifying-value-of-a-local-variable-given-as-function-parameter)**  \n    * **[0x05 ~ Unprotected Malloc](#0x05--unprotected-malloc)**  \n    * **[0x06 ~ Freeing memory that has already been fred](#0x06--freeing-memory-that-has-already-been-fred)**  \n    * **[0x07 ~ Do Not Use Global Variables](#0x07--do-not-use-global-variables)**  \n    * **[0x08 ~ Variable Length Arrays](#0x08--variable-length-arrays)**  \n    * **[0x09 ~ Using ft_ prefix for all functions](#0x09--using-ft_-prefix-for-all-functions)**  \n    * **[0x0A ~ Usage of Sequence Point](#0x0a--usage-of-sequence-point)**  \n    * **[0x0B ~ Assignment of read-only location](#0x0b--assignment-of-read-only-location)**  \n    * **[0x0C ~ Carefully use define preprocessor macros](#oxoc--carefully-use-define-preprocessor-macros)**  \n    * **[0x0D ~ Comparing Float and Double](#0x0d--comparing-float-and-double)**  \n    * **[0x0E ~ Wrong usage of pointers](#0x0e--wrong-usage-of-pointers)**  \n    * **[0x0F ~ Undefined Behavior](#0x0f--undefined-behavior)**  \n\t* **[0x10 ~ Operator Precedence](#0x10--operator-precedence)**  \n\n---\n* **[2. Clean Code](#snowflake-clean-code)**  \n    * **[0x00 ~ Meaningful and Explicit Names](#0x00--meaningful-and-explicit-names)**  \n    * **[0x01 ~ Write short functions](#0x01--write-short-functions)**  \n    * **[0x02 ~ Using structure for basic items](#0x02--using-structure-for-basic-items)**  \n    * **[0x03 ~ Using flags for projects' options](#0x03--using-flags-for-projects-options)**  \n    * **[0x04 ~ Using gcc flags for Makefile](#0x04--using-gcc-flags-for-makefile)**  \n    * **[0x05 ~ Using preprocessor DEBUG macros](#0x05--using-preprocessor-debug-macros)**  \n\t* **[0x06 ~ Branching Optimization](#0x06--branching-optimization)**\n\t* **[0x07 ~ Reserved Keywords](#0x07--reserved-keywords)**  \n\n---\n* **[3. Programmer Tools](#programmer-tools)**      \n    * **[0x00 ~ Code Editors](#0x00--code-editors)**  \n    * **[0x01 ~ Terminal Bash](#0x01--terminal-bash)**  \n    * **[0x02 ~ Git](#0x02--git)**  \n    * **[0x03 ~ Productivity Gains](#0x03--productivity-gains)**  \n    * **[0x04 ~ Add a a new binary in the PATH environment variable](#0x04--add-a-a-new-binary-in-the-path-environment-variable)**  \n    * **[0x05 ~ Computer Graphics Libraries](#0x05--computer-graphics-libraries-ubuntu)**  \n\n---\n* **[4. Curated list of Programming Learning Materials](#gem-curated-list-of-programming-learning-materials)**  \n    * **[0x00 ~ C Knowledge](#0x00--c-knowledge)**  \n    * **[0x01 ~ Algorithm](#0x01--algorithm)**  \n    * **[0x02 ~ Bitwise Manipulations](#0x02--bitwise-manipulations)**  \n    * **[0x03 ~ Network](#0x03--network)**  \n    * **[0x04 ~ Hacking \u0026 Security](#0x04--hacking--security)**  \n    * **[0x05 ~ Computer Graphics](#0x05--computer-graphics)**  \n    * **[0x06 ~ Computer Vision \u0026 AI](#0x06--computer-vision--ai)**  \n    * **[0x07 ~ C++ Optimization](#0x07--c-optimization)**  \n    * **[0x08 ~ Assembly Optimization](#0x08--assembly-optimization)**  \n    * **[0x09 ~ Functional Programing](#0x09--functional-programing-by-leonard-marquez)**  \n\t* **[0x0A ~ Computer Architecture](#0x0a--computer-architecture)**\n    * **[0x0B ~ Misc](#0x0b--misc)**  \n    * **[0x0C ~ Science-Fictions Masterpieces](#0x0c--science-fiction-masterpieces)**  \n\n---\n* **[5. Tutorials](#tutorials)**  \n    * **[0x00 ~ Optimization - Aiming for the lowest latency](#0x00--optimization---aiming-for-the-lowest-latency)**  \n        * **[Optimization flags](#optimization-flags)**  \n        * **[Multithreading and Parallelization](#multithreading-and-parallelization)**  \n        * **[Vectorization](#vectorization)**  \n        * **[Combining Optimization Flags, Parallelization and Vectorization](#combining-optimization-flags-parallelization-and-vectorization)**  \n        * **[The right algorithm](#the-right-algorithm)**  \n\t\t* **[Exploring Compiler's Assembly Output](#exploring-compilers-assembly-output)**  \n    * **[0x01 ~ Computer Graphics - Using SDL2 to create Fractal](#0x01--computer-graphics---using-sdl2-to-create-fractal)**  \n        * **[Using SDL2 to create Computer Graphics](#using-sdl2-to-create-computer-graphics)**  \n        * **[Example with a Barnsley Fern Fractal](#example-with-a-barnsley-fern-fractal)**  \n    * **[0x02 ~ Hacking - Buffer Overflow](#0x02--hacking---buffer-overflow)**  \n        * **[Introduction](#introduction)**  \n        * **[Buffer overflow to hijack a password](#buffer-overflow-to-hijack-a-password)**  \n        * **[Shellcode Execution to get root access](#shellcode-execution-to-get-root-access)**  \n\n---\n* **[6. Epilogue]()** \n    * **[0x00 ~ Wanted PR](#0x00--wanted-pull-requests)**  \n    * **[0x01 ~ Question ? Broken Link ? Wanna contribute ?](#0x01--question--broken-link--wanna-contribute-)**  \n    * **[0x02 ~ Liked it ?](#0x02--liked-it-)**  \n    * **[0x2A ~ About the Author](#musical_score-0x2a--about-the-author)**  \n\n*NB: Use CTRL + F or Command + F to quickly look for keywords.*\n\n---\n# About 42 School\n\n---\n## 0x00 ~ What is 42 School\n\n\u003e 42 is more than just a disruptive educational model and coding school. What makes us unique and a major player in the tech world are the defining characteristics of the 42 culture. Every element of 42 shows our culture, from the students, to the curriculum structure and content, to the $0 tuition and innovative admissions process.\n\nThat's right, the school is FREE, originally funded and founded in Paris by generous **philanthropist billionaire [Xaviel Niel](https://en.wikipedia.org/wiki/Xavier_Niel)**.\n\n\u003e **I'm not unusual; it's the others who are strange** ― *Xavier Niel*\n\nThe name of the school, \"42\", is a tribute to [The Hitchhiker's Guide to the Galaxy](https://en.wikipedia.org/wiki/The_Hitchhiker%27s_Guide_to_the_Galaxy), a comedy science fiction series created by Douglas Adams.\n\n\u003e 42, or The Answer to the Ultimate Question of Life, The Universe, and Everything\n\nThe supercomputer had this function ready:\n```c\n#include \u003cstdio.h\u003e\n\n#define true  1\n#define false 0\n\nint what_is_forty_two(void) {\n    int n = true \u003c\u003c 1 | false; // n = 0b10;\n    while (__builtin_popcount(n) != 3) // stop when reaching 3 bits set\n        n |= n \u003c\u003c 2;  // n adds two empty bits with \u003c\u003c 2 (x4) and add itself with |\n    return (++n == '*') ? n : !!n * (n - 1); // you may simply return n;\n}\n\nint main(void) {\n    char *question = \"What is the answer to Life, the Universe and Everything?\\n\";\n    printf(\"%sDeep Thought: %d\\n\", question, what_is_forty_two()); // %s print a string, and %d an integer\n    return 0;\n}\n```\n\nThere are no teachers but a pedagogic team that ensure that students do not harm the material and provide a cursus syllabus to follow. What is learned is hence mainly achieved through peer-to-peer project review and [RTFM](https://en.wikipedia.org/wiki/RTFM).\n\n![RTFM meme](https://i.kym-cdn.com/photos/images/newsfeed/000/017/668/Mao_RTFM_vectorize_by_cmenghi.png?1318992465)\n\nMost of the entrance exam and early cursus is done in [C language](https://en.wikipedia.org/wiki/C_(programming_language)).  \n\n\u003e **Nevertheless, C retains the basic philosophy that programmers know what they are doing; it only requires that they state their intentions explicitly.** ― *Brian W. Kernighan, The C Programming Language*\n\nC is the most pedagogic programming language you can learn as it allows to understand the basis of programming from simple concepts like **conditions** {if, elseif, else}, **loops** {while, do while, for}, **write system calls** and **pointers** to more advanced one like **function pointers** and **memory allocation**.\n\nLater on you can specialize in other languages: Python will fit data scientists and devops, javascript for frontend developers and C# for those looking for a career in finance.\n\n\u003e **When you say 'I wrote a program that crashed Windows,' people just stare at you blankly and say 'Hey, I got those with the system, for free.'** ― *Linus Torvalds*\n\nYou will learn how to do what [Muggles](https://en.wikipedia.org/wiki/Muggle) were only able to do accidentally.\n\n---\n## 0x01 ~ For Candidates: About the \"Piscine\"\n\n\u003e **If you're going through hell, keep going.** ― *Winston Churchill*\n\nThe piscine is the entrance exam that consists of **4 weeks fully dedicated to coding**, solving exercises and submitting solo and group projects to peer review.  \n\n**It does not matter if you fail a project, an exam or a day as long as you keep striving**. Someone who has never been interested before in Computer Science would never be able to complete everything in time, yet he will not prevent from being successful.\n\n### :coffee: My guess on the success criteria\n* **0x00 Come as you are** ... or forget this bullshit and prepare a little bit with [subjects on github](https://github.com/Binary-Hackers/42_Subjects/tree/master/01_Piscines/C/EN), courtesy of my friend binary hacker.\n\n* **0x01 Prepare to nail the exams** on the 4 exams session, knowing that the 3 firsts exams are limited in term of how far you can go and it is not a big deal to miss the first 3 exams as the most important is IMHO the maximum level you can reach. **Succeeding the first 4 exercises (36 pts)** should be enough to make sure you quality.\n\n* **0x02 Get an acceptable percentage of review from peers** (probably 80% is enough, but you would get 90 to 97% if you are nice). *Don't be too nice, but don't be a dick with [vim .swp files](https://lmgtfy.com/?q=What+is+the+purpose+of+swap+files%3F) and .DS_Store*.\n\n\u003e  [.DS_Store](https://en.wikipedia.org/wiki/.DS_Store) – The name of a file in the Apple OS X operating system for storing custom attributes of a folder such as the position of icons or the choice of a background image. These files are created when you manipulate your files with the [Finder GUI](https://en.wikipedia.org/wiki/Graphical_user_interface).\n\n* **0x03 The logging time has no or very little influence**, I know it as a fact for seeing people constantly logged in (but slacking) failing the piscine and students barely present being accepted. However the more time you spend in 42 school will certainly directly influence your skills and positively impact other related topics\n\n* **0x04 It is strongly recommended to succeed at least one group project**, especially the first one that is really easy.\n\n* **0x05 There is a special and unique achievement awarded to the most helpful/smart student.** This achievement does not show up on the student profile until he asks for it.\n\n* **0x06 Be aware of the different rules** : Many things are forbidden like declaring and assigning a variable in the same line, using printf or using for loops. The daily assignment must be pushed on git before Day + 1 at 11pm42.\n\n* **0x07 [Boys Only] Don't waste time flirting** : For some who have been living in the basement of their parents' house for years it is a good opportunity to see what a girl looks like in real life. Nevertheless, you have to under that 1/this is not the right time and place to do so.\n\n* **0x08 You can sleep in the school during the selection** - *I recommended you to not do it, you will have very poor sleep.* - If you still go for it here is a list of essential items you should bring: **a toothpaste, a toothbrush, a soap and a towel on top of your phone, charger and mattress. Oh and a credit card also, unless you prefer to bring 10kg of cookies**\n\nSo whatever how dire the situation is looking (you failed all your days, exams etc), if you can keep your enthusiasm and your spirit up, you will eventually succeed !\n\n\u003e **“Success is stumbling from failure to failure with no loss of enthusiasm.** ― *Winston Churchill*\n\n[I made a video on how to make sure that you succeed the entrance exam](https://www.youtube.com/watch?v=dQw4w9WgXcQ)\n\n### :star: List of Essential Items\n\n\u003e **Towels are extremely useful for cleaning up messes and drying off your body. You can set it on fire as a weapon, chase off enemies, and use it as a distress signal. Life is messy and sometimes dangerous. Space is even messier and more dangerous. Be like Arthur Dent and keep up with your towel** ― *[17 Life Lessons From HITCHHIKER’S GUIDE Hero Arthur Dent](https://nerdist.com/article/hitchhikers-guide-life-lessons-arthur-dent/?amp)*\n\n:sleeping_bed: Mattress or equivalent and Pillow  \n:electric_plug: Phone charger  \n:iphone: Phone  \n:droplet: Toothpaste and Toothbrush  \n:bathtub: Soap and 2-4 Towels  \n:money_mouth_face: Credit Card  \n:heart: Kleenex  \n\n\n---\n## 0x02 ~ Coding simple C programs\n\n\u003e **시작이 반이다** ― *The beginning is half of the way (Korean proverb)* \n\n### First by installing a C compiler on your computer\n* On Windows it is a bit tricky, you will have to install [Mingw](http://www.mingw.org/)\n* On Linux it is pretty straightforward since it is only installed and if not ```apt-get``` will make it easy.\n* On MAC it is not much more difficult, google how to do it.\n\n### C Data Types\n\nI will only list the main ones\n\n|Data Type|Bytes|Description|\n|-|-|-|\n|char|1|Used for text\n|bool|1|Used to return true or false, you will need the header \u003cstdbool.h\u003e\n|short|2|Half the size of an integer, used to optimize memory\n|int|4|Loop Counter, operations on integers\n|long|8|Twice the size of an integer, used when overflow is a problem\n|float|4|Used for computer graphics\n|double|8|Used for computer graphics, more precised than float but takes more memory\n|unsigned|.|Apply to char, short, int and long, means than it cannot have negative values\n\nYou should then try to recode basic C functions\n\n### Pointers\n\n\u003e [In computer science, a pointer is a programming language object that stores a memory address.](https://en.wikipedia.org/wiki/Pointer_(computer_programming))\n\n**Pointer is a fundamental concept of C programming**.\n\n**You can think of your computer's memory as a contiguous array of bytes**. Each time that you make an innocent declaration and assignation such as **`int a = 5`**, this value is written into your computer's memory on 4 bytes (integer size).\nThis value will be written at a specific memory address, the **stack** (fast access to memory) if no memory allocation, else it will be stored deeper in the **heap**. This address also has a value!\n\n\n*Example illustrating the difference a pointer - a memory address pointing to value - and a value:*\n\n```c\n#include \u003cstdio.h\u003e\n\nint main(void) {\n\tint a = 5;\t// declaring an integer variable and assigning the value of 5\n\tint *ptr;\t// declaring a pointer to integer\n\tint b;\t\t// declaring an integer variable\n    printf(\"ptr's value: %2d, ptr's address: %p\\n\\n\", *ptr, ptr);\n\n\tptr = \u0026a;\t// pointer ptr points to what is stored at the memory address of variable a\n\tb = a;\t\t// b will take the value and not the address\n\ta = 42;\t\t// b is still equal to 5, but ptr will return 42, which is the value now stored at a's location;\n\tprintf(\"  a's value: %2d,   a's address: %p\\n\", a, \u0026a);\n\tprintf(\"ptr's value: %2d, ptr's address: %p\\n\", *ptr, ptr); // you will get the same as above, notice that you have to dereference the pointer with * to get the value, and using the pointer alone (ptr) will give you the memory address.\n\tprintf(\"  b's value: %2d,   b's address: %p\\n\", b, \u0026b);\n\t//printf(\"Size of ptr: %zu\\n\", sizeof(ptr)); // size of ptr in bytes, 8 on my system.\n\treturn 0;\n}\n```\n\nYou will get this kind of output:\n```\nptr's value:  1, ptr's address: 0x7ffd99493000\n\n  a's value: 42,   a's address: 0x7ffd99492f08\nptr's value: 42, ptr's address: 0x7ffd99492f08  \u003c-- they now match thanks to ptr = \u0026a\n  b's value:  5,   b's address: 0x7ffd99492f0c\n```\n\n**NB: On the second printf you will get the value that you got for `a`, notice that you have to dereference the pointer with * to get the value, and using the pointer alone (ptr) will give you the memory address.**\n\n\n#### [About Endianness](https://en.wikipedia.org/wiki/Endianness).\n\nValues are stored differently depending on the kind of system you are using.\n\nLittle endian means that the value is stored in memory from left to right, big endian means it is stored from right to left.\n\n*[See this example with int a = 9](https://stackoverflow.com/questions/12791864/c-program-to-check-little-vs-big-endian/12792301#12792301):*\n\n```\nlittle endian: \n\n       higher memory\n          -----\u003e\n    +----+----+----+----+\n    |0x09|0x00|0x00|0x00|\n    +----+----+----+----+\n    |\n   \u0026x = 0xff\n\n\nbig endian:\n    +----+----+----+----+\n    |0x00|0x00|0x00|0x09|\n    +----+----+----+----+\n    |\n   \u0026x\n```\n\n*To find out if your system is big or little endian you can use the [following function](https://stackoverflow.com/questions/4181951/how-to-check-whether-a-system-is-big-endian-or-little-endian/4181991):*\n```c\nint x = 9;\n\nif (*(char *)\u0026x == 0x09) // we cast x as a byte to get its very first byte, it will return true (meaning little endian) if the first byte is equal to 9.\n```\n\n### ft_putchar\n\n*A minimalist c program that will puzzle beginners, write it in a file named a.c and create a.out with ```gcc a.c \u0026\u0026 ./a.out```*\n\nThe following program will print a char by making use of [write](http://man7.org/linux/man-pages/man2/write.2.html)\n\n```c\n#include \u003cunistd.h\u003e\n\nvoid\tft_putchar(char c) // void because the function does not return any value, it writes directly, char is the type of the variable c that is given as parameter to the function ft_putchar by the main function.\n{\n\twrite(1, \u0026c, 1);\t\t\t// ssize_t write(int fd, const void *buf, size_t count); or in human language: write count letters of buf (which is a pointer) to fd (if fd = 1 this is your terminal, stdout)\n}\n\nint\tmain(void) {\n\tft_putchar(42);\t\t\t\t// will print a star\n\t// ft_putchar(42 + '0');\t// will only print 4\n\t// ft_putchar(\"4\");\t\t\t// will not work, you are using \" instead of ', so C language think it is a char array.\n\treturn 0;\n}\n```\n\nOnce you understand well how to print a character, you should try to return the length of many together (it is called a [string](https://en.wikipedia.org/wiki/String_(computer_science)))\n\n### ft_strlen\n\n```c\n#include \u003cunistd.h\u003e\n\nint\t\tft_strlen(char *str) {\n\tint i = 0;\t\t\t\t\t// set variable i to 0\n\twhile (str[i] != '\\0')\t\t// while the char array does not reach a NULL character\n\t\ti++;\t\t\t\t\t// increment i, equivalent of i = i + 1;\n\n\treturn i;\t\t\t\t\t// return i variable to the caller function\n}\n\nint main(void) {\n\tint i = ft_strlen(\"Duck Tales\");\t// declare i, call the function ft_strlen, and assign its output to i\n\tprintf(\"%d\", i); // remember that it is forbidden to submit a function with printf during the Piscine\n\treturn 0;\n}\n```\n*NB: remember that it is forbidden to submit a function with printf during the Piscine*\n\n### ft_putstr\n\nThen print a whole string by recoding the libc function 'puts':\n```c\n#include \u003cstdio.h\u003e // header for puts\n\nint main(void) {\n\tputs(\"Duck Tales\");\n\treturn 0;\n}\n```\n\nThis can be achieve by using and index that starts on the first character and is progressively incremented until NULL as string are NULL terminated:\n```c\n#include \u003cunistd.h\u003e\n\nvoid\tft_putstr(char *str) {\n\tint i = 0;\n\n\twhile(str[i] != '\\0')\n\t\twrite(1, \u0026str[i++], 1);\n}\n```\n\nAlong with the main function slightly modified to make use of your code:\n```c\nint main(void) {\n\tft_putstr(\"Duck Tales\");\n\treturn 0;\n}\n```\n\nYou can also use only the pointer since you do not care of the return value (the function type being void)\n```c\n#include \u003cunistd.h\u003e\n\nvoid\tft_putstr(char *str) {\n\twhile(*str)\n\t\twrite(1, s++, 1);\n}\n```\n\nOr even use the length of the string to print the whole string at once, hence avoiding many *[system calls](https://en.wikipedia.org/wiki/System_call) (write)* that are costly for the program execution:\n\n```c\nvoid\tft_putstr(char *str) {\n\twrite(1, str, ft_strlen(str));\n}\n```\n*NB: You have to include ft_strlen in the same file AND above the function to make it work.*\n\nNext you should **study the different concepts in programming**, especially spend time understanding the different [C data types](https://en.wikipedia.org/wiki/C_data_types), [the concept of pointers](https://en.wikipedia.org/wiki/Pointer_(computer_programming)) and [arrays](https://en.wikipedia.org/wiki/Array_data_type), because it is what you have been using up to now and it will only get more complicated.\n\n\n---\n## 0x03 ~ 42 Projects Guides\n\n\u003e **Do what you think is interesting, do something that you think is fun and worthwhile, because otherwise you won’t do it well anyway.** ― *Brian W. Kernighan*\n\n|Name|Track|Hashtags|What you will learn|\n|-|-|-|-|\n|Fillit|General|Architecture, Parsing, Algo|[Description from a student](https://medium.com/@bethnenniger/fillit-solving-for-the-smallest-square-of-tetrominos-c6316004f909)|\n|Printf|Algorithm|Architecture, Parsing, utf-8|[UTF-8 Conversion table](https://en.wikipedia.org/wiki/UTF-8)\u003cbr\u003e[Variadic Function](https://en.wikipedia.org/wiki/Variadic_function)|\n|[Filler](https://github.com/agavrel/42-filler)|Algorithm|Parsing, Algo, Bot|42 forums have good threads on this project|\n|Lem-In|Algorithm|Parsing, Algo, Chained-Lists|[Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)|\n|Corewar|Algorithm|Architecture, parsing, disassembler, virus, VM|[About the original Game](https://en.wikipedia.org/wiki/Core_War)|\n|LS|System|Parsing, Recursion, Chained-Lists|[The Good Old Manual](http://man7.org/linux/man-pages/man1/ls.1.html)|\n|Minishell|System|Environment Variables, Shell|[Bourne Shell](https://en.wikipedia.org/wiki/Bourne_shell)|\n|Malloc|System|Algo, Memory, HashCollision|[The Good Old Manual](http://man7.org/linux/man-pages/man3/malloc.3.html)|\n|FDF|Computer Graphics|Parsing, Creativity|[Bresenham's line algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm), [Use of Graphics Library](https://en.wikipedia.org/wiki/Graphics_library), [Trigonometry](https://en.wikipedia.org/wiki/Trigonometry), [Rotations](https://en.wikipedia.org/wiki/Rotation_(mathematics)), [3D Projection](https://en.wikipedia.org/wiki/3D_projection), [ARGB Color Space](https://en.wikipedia.org/wiki/RGBA_color_space)|\n|Fractol|Computer Graphics|Fractals, Mathematics, ARGB, HUV|[Mandelbrot Set](https://en.wikipedia.org/wiki/Mandelbrot_set)|\n|[Cube3d - Wolf3d](https://lodev.org/cgtutor/raycasting.html)|Computer Graphics|Ray Casting, Rotation|[About the original Wolfenstein 3d](https://en.wikipedia.org/wiki/Wolfenstein_3D)|\n|NmOtool|System|Symbol Table, .dll .so|[Implement List the symbols in a .so file](https://stackoverflow.com/questions/34732/how-do-i-list-the-symbols-in-a-so-file)\n|LibftAsm|System|x86 Assembly Instructions|[Refer to the Intel Bible](https://software.intel.com/en-us/articles/intel-sdm)\n|[RT](https://github.com/Chr0nos/rt)|Computer Graphics|Ray Tracing|Create a Scene of enlightened polygons \n|[Scop](https://github.com/Gpinchon/Scop42)|Computer Graphics|Shading|Create a Shader\n|Particles System|Computer Graphics|Graphics Effects|[simulate certain kinds of \"fuzzy\" phenomena](https://en.wikipedia.org/wiki/Particle_system)\n\n---\n## 0x04 ~ Choosing your Path\n\n\u003e **Never give up on something that you can't go a day without thinking about** ― *Winston Churchill*\n\n### How to choose your specialization\n\nThere are currently 4 main branches: [Infographics](https://en.wikipedia.org/wiki/Infographic), Algorithms, System and Web.\nAll branchs are interesting and you should try to explore each branch's initial project:\n* If you are aiming to work in the video game industry and like Mathematics then you should go for **Infographics**. Remember that this path is tough and not necessarily as rewarding as the other ones, but you will have the luxury to work in the video game industry.\n* **Algorithm branch** is/was mainly based on flawless parsing and not so much on algorithm quality. Fortunately with the nomination of Benny as the head of the Pedagogy there will be more efforts to reward smart algorithms. Algorithms is the best one if you want to join a prestigious company like Google\n* **System** is the best for those who like security, network and how computers truly work since you will have to ultimately recode your own operating system.\n* **Web** is good for those who like to build websites, perhaps mobile app as well (react native) and want to become a freelancer.\n\n\n---\n## 0x05 ~ Swindle the norminette - *truander la norme*\n\n### While loops\n\n*Only 25 lines ? No problem:*\n```c\nint draw_lines(int len) { // NB: len is positive or equal to 0\n\tint i;\n\t\n\ti = 0;\n\twhile (i \u003c len)\n\t{\n\t\tputs(\"Looping\"); // NB: you will have to use your own function, ft_putstr, of course\n\t\tdraw_lines(i);\n\t\ti++;\n\t}\n}\n```\n**Originally 9 lines**\n\n```c\nint draw_lines(int len) {\n\tint i;\n\n\ti = -1;\n\twhile (++i \u003c len \u0026\u0026 puts(\"Looping\"))\n\t\tdraw_lines(i);\n}\n```\n**Now 5 lines**\n\n```c\nint draw_lines(int len) {\n\twhile (--len \u003e= 0 \u0026\u0026 puts(\"Looping\")) // it works\n\t\tdraw_lines(len); // NB: make sure that drawing backward does not impact algo\n}\n```\n**2 lines**\n\n```c\nint draw_lines(int len, int i) { // If you really need to call from 0 to len then you can also have i passed as a parameter = -1\n\twhile (++i \u003c len \u0026\u0026 puts(\"Looping\"))\n\t\tdraw_lines(i);\n}\n```\n**2 lines, with prototype modification (ugly)**\n\n\n---\n### [If brackets](https://github.com/keuhdall)\n\n```c\nif (true)\n{\n\tfunc1();\n\tfunc2();\n}\n```\n**5 lines**\n\n```c\nif (true)\n\tfunc1();\nif (true)\n\tfunc2();\n```\n**4 lines**  \n\n**NB: Beware of these tricks, it could potentially make your program less efficient. In the above example you use two [branching instructions](https://en.wikipedia.org/wiki/Branch_(computer_science)) - *if* - instead of one and in the while example the -1 initialization and puts inside the while hinder readability**\n\n---\n### [Write colorful usage](https://github.com/mrdotb)\n```c\nint\tusage(void)\n{\n\tstatic char usage_str[] =\n\n\tGREEN\"philo_one\\n\"RESET\n\t\"Simulation of the philosopher.\\n\\n\"\n\tYELLOW\"USAGE:\\n    \"RESET\n\tGREEN\"philo_one \"RESET\n\t\"number_of_philosopher time_to_die time_to_eat \"\n\t\"time_to_sleep [number_of_time_each_philosophers_must_eat]\\n\\n\"\n\tYELLOW\"ARGS:\\n    \"RESET\n\t\"All args must be positive integer\\n\";\n\tft_putstr_fd(usage_str, 1);\n\treturn (1);\n}\n```\n\n---\n### [Function Pointers](https://github.com/mrdotb)\n\n```c\nvoid\t\t\tlisten_keystroke(t_dlist **lst)\n{\n\tchar\t\tbuffer[8];\n\tint\t\t\tel;\n\tstatic void\t(*f[])(t_dlist **lst) = { lst_validate, lst_del_one,\n\t\tlst_del_one, lst_move_left, lst_move_right, lst_move_up,\n\t\tlst_move_down, lst_select, lst_esc, lst_void_ret};\n\n\tft_memset(buffer, 0, 8);\n\twhile (read(0, buffer, 8) != -1)\n\t{\n\t\tel = ft_chrmatch(buffer);\n\t\tf[el](lst);\n\t\trender(find_first(lst), 0);\n\t\tft_memset(buffer, 0, 8);\n\t}\n}\n```\n\n---\n## 0x06 ~ Impossible is not C\n\n### Negative index Array\n\n```c\n#include \u003climits.h\u003e\t// INT_MAX\n#include \u003cstdio.h\u003e\t// printf\n\nint main(void) {\n\tint x[2001];\n\tint *y = \u0026x[1000];\n\n\t(void)x;\n\ty[-10] = 5;\n\tprintf(\"%d\\n\", y[-10]);\n}\n```\n\n### It's just a pointer game\n\nDid you know ? Instead of writing array[index], you can write index[array]:\n```c\nint ft_strlen(char *str) {\n\tint i = 0;\n\twhile (i[str])\n\t\t++i;\n\n\treturn i;\n}\n```\n\nBecause this is understood by the compiler as pointer arithmetic:\n```c\nint ft_strlen(char *str) {\n\tint i = 0;\n\twhile (*(str+i))\n\t\t++i;\n\n\treturn i;\n}\n```\n\n### Get function name, filename or even line number\n\n```__FILE__```, ```__FUNCTION__``` and ```__LINE__``` macros can be very helpful to display meaningful error messages for both users and developers:\n\n```c\n#include \u003cstdbool.h\u003e\t// bool\n#include \u003cunistd.h\u003e\t\t// write\n#include \u003cstdlib.h\u003e\t\t// malloc\n#include \u003cstring.h\u003e\t\t// strlen\n#include \u003cstdarg.h\u003e\t\t// va_list\n\nbool\tft_error_va(char *errmsg, ...) {\n\tva_list\t\targs;\n\tchar\t\t*arg = errmsg;\n\n\twrite(2, errmsg, strlen(errmsg));\n\tva_start(args, errmsg);\n\twhile (arg = va_arg(args, char*)) {\n\t\twrite(2, arg, strlen(arg));\n\t}\n\twrite(2, \"\\n\", 1);\n\tva_end(args);\n\treturn false;\n}\n\nchar\t*ft_itoa(int n);\n\nbool\tft_error(char *errmsg, char *file, const char *function, int line) {\n\t return ft_error_va(errmsg, \"File: \", __FILE__,  \", in function \", \\\n\t (char *)function, \", line \", ft_itoa(line), NULL);\n}\n\n\nbool\tdummy_function(void) {\n\t if (3 != 2)\n\t \treturn ft_error(\"Error with 3 != 2: \", __FILE__, __FUNCTION__, __LINE__);\n}\n\nint\t\t\tmain(void) {\n\tif (!dummy_function())\n\t\treturn 1;\n\treturn 0;\n}\n\nchar\t*ft_itoa(int n)\n{\n\tchar\t*s;\n\tlong\ttmp;\n\tint\t\tlength;\n\n\ttmp = n;\n\tlength = (n \u003c= 0 ? 2 : 1);\n\twhile (n \u0026\u0026 ++length)\n\t\tn /= 10;\n\tif (!(s = (char *)malloc(sizeof(char) * length)))\n\t\treturn (NULL);\n\ts[--length] = '\\0';\n\tif (tmp \u003c= 0)\n\t\ts[0] = (tmp \u003c 0 ? '-' : '0');\n\twhile (tmp)\n\t{\n\t\ts[--length] = (tmp \u003c 0 ? -tmp : tmp) % 10 + '0';\n\t\ttmp /= 10;\n\t}\n\treturn (s);\n}\n```\nIf you don't know what variadic functions are, ```#include \u003cstdarg.h\u003e```, you can check [my implementation of printf](https://github.com/agavrel/42-ft_printf/blob/master/srcs/ft_printf.c)\n\n### Setting values of a struct to 0 without using memset or bzero\n\nYou can use either:\n```c\nt_mystruct mystruct = {};\n```\n\nor, to comply with 42 Norminette that forbid declaration and assignation on the same row:\n```c\nt_mystruct mystruct;\nmystruct = (t_mystruct){};\n```\n\n\n---\n# :fire: Common Beginner Mistakes\n\n\u003e **Experience is the name everyone gives to their mistakes** – *[Oscar Wilde](https://en.wikipedia.org/wiki/The_Picture_of_Dorian_Gray)*\n\n---\n## 0x00 ~ Array overflow\n\nIn C the index of an array starts at 0. Because C does not perform boundary checking when using arrays, if you access outside the bounds of a stack based array it will just access another part of already allocated stack space, like in this example:\n\n```c\n#include \u003cstdio.h\u003e\n\nvoid    somefunction3(void)\n{\n    int a[5] = {1,3,5,7,9};\n    printf(\"%d\\n\", a[5]);\n}\n```\nIn this example, 5 is the size of the array and if you try to access it it will overflow. Remember that the maximum array index you can ever access is its size minus 1.\n\nI would suggest to use as much as possible a const :\n```c\n#include \u003cstdio.h\u003e\n\nvoid    somefunction3(void)\n{\n\tconst int len = 5;\n\tint a[len] = {1,3,5,7,9};\n\tfor (int i = 0; i \u003c len; i++) // safe\n\t\tprintf(\"%d\\n\", a[i]);\n}\n```\n\n---\n## 0x01 ~ Segmentation Fault\n\n\u003e **There are two ways to write error-free programs; only the third one works** – *Alan J. Perlis*\n\n*Many potential reasons for this...*\n\n\n---\n## Loop segfault\nOne common mistake is that you had declared a loop and either:\n\n#### Forgot to increment the counter\n\n```c\nint i = 0;\n\nwhile (i \u003c 10)\n{\n\twrite(1, \u0026i + '0', 1);\n\t// but where is i++ ?\n}\n```\n\n#### Correct way\n\n```c\nint i = 0;\n\nwhile (i \u003c 10)\n{\n\twrite(1, \u0026i + '0', 1);\n    \ti++;\n}\n```\n\n### Forgot the exit condition:\n\n```c\nint somevariable = 0;\nwhile (42) // always True ! You will be 42 for life ;)\n{\n    // call to some stuff that never succeed to set someVariable to 1;\n    if (somevariable == 1) // make sure that somevariable will equal 1 at some point.\n        break ;\n}\n```\n\n### Used an assignation = instead of a boolean expression != == \u003c= \u003e=\n\n```c\n#include \u003cstdio.h\u003e\n\nint main(void) {\n\tunsigned int x = 10;\n\n\twhile (--x != 0)\n\t{\n\t\tprintf(\"0 0 0 1 0 1 0 1 0 \");\n\t\tif (x = 1) {\t\t\t// oopsie !!\n\t\t\tprintf(\"* \");\n\t\t\tx--;\n\t\t}\n\t}\n\treturn 0;\n}\n```\n*PS: will you be able to fix this code ?*  \n\nAlso classic with lists:  you have a loop and its crucial condition that allows the function to return, but used an assignation instead of comparison\n```c\nint i = 0;\n\nwhile (list)\n{\n    if (list = NULL) // You want to use if (list == NULL)\n        return i;\n    i++;\n    list=list-\u003enext;\n}\nreturn -1; // will always return -1\n```\n\n### Quizz: What will print this loop ?\n\n```c\nunsigned char c = 0;\n\nwhile (c \u003c 150)\n{\n\twrite(1, \u0026c, 1);\n\tc++;\n}\n```\n\n\u003e **Talk is cheap. Show me the code** ― *Linus Torvalds*\n\n\n### Accessing the next link in a chained-list without checking the current one\n\nAnother example with linked-lists\n```c\ntypedef struct  s_list {\n      void      *data;\n      t_list    *next;\n }              t_list;\n\n/*\n** function to go 2 links further in a chained-list\n*/\n\nvoid somefunction(t_list *list)\n{\n    if (list-\u003enext != NULL)\n    {\n        list = list-\u003enext-\u003enext;\n    }\n}\n```\n\nif the current link of list is null you will get a segfault. The correct way is to always check the current link before the next one:\n```c\nvoid somefunction(t_list *list)\n{\n    if (list \u0026\u0026 list-\u003enext) // if both list and list-\u003enext exist\n        list = list-\u003enext-\u003enext;\n}\n```\n\n### Accessing an index in a loop for program with either graphics or a board game\n```c\nint somefunction(int y_max, int x_max, int array[y_max][x_max]);\n{\n    int y;\n    int x;\n\n    y  = 0;\n    while (y \u003c y_max)\n    {\n        x = 0;\n        while (x \u003c x_max)\n        {\n            if (array[y][x-1] \u003e array[y][x]) // don't you see there is a problem ?\n                array[y][x] = array[y][x-1];\n            if (array[y+1][x] \u003e array[y][x]) // don't you see there is another problem ?\n                array[y][x] = array[y+1][x];\n        }\n\n    }\n}\n```\n\nThese lines should be corrected the following way:\n```c\nif (x \u003e 0 \u0026\u0026 array[y][x-1] \u003e array[y][x])\nif (y \u003c y_max - 1 \u0026\u0026 array[y+1][x] \u003e array[y][x]) // strictly inferior to last possible index which is y_max - 1,\n// you may also write y \u003c= y_max - 2\n```\n\nYou may also notice that we can even do better by changing the starting value of x or the exit condition of the y loop **in the case that we were to check only one of the two if conditions.**\n```c\nx = 1;\nwhile (y \u003c y_max - 1)\n```\n\nAnother example\n```c\nint main(void) {\n\tconst int x_max = 3;\n\tconst int y_max = 3;\n\tint a[y_max][x_max];\n\t\n\tfor (int y = 0; y \u003c y_max; y++)\n    \tfor (int x = 0; x \u003c x_max; x++)\n\t\t\ta[y+6][x] = x + y;\n}\n```\n\n---\n## 0x02 ~ Bus error\n\nOccur when your processor cannot even attempt the memory access requested, like trying to access an address that does not satisfy its alignment requirements.\n```c\nint main(void) {\n\tconst int x_max = 3;\n\tconst int y_max = 3;\n\tint a[y_max][x_max];\n\t\n\tfor (int y = 0; y \u003c y_max; y++)\n    \tfor (int x = 0; x \u003c x_max; x++)\n\t\t\ta[y][x] = a[x] + a[y];\n}\n```\n\n\n---\n## 0x03 ~ Stack smashing\n\nSee below in the recommended books the one by Aleph One, how you can make use of such \"error\"\n```c\nint main(void) {\n\tconst int x_max = 3;\n\tconst int y_max = 3;\n\tint a[y_max][x_max];\n\t\n\tfor (int y = 0; y \u003c y_max; y++)\n    \tfor (int x = 0; x \u003c x_max; x++)\n        \ta[y][x] = x + y;\n\n\tfor (int y = 0; y \u003c y_max; y++) {\n    \tfor (int x = 0; x \u003c x_max; x++) {\n        \ta[y+6][x] += a[y][x];\n    \t}\n\t}\n}\n```\n\n---\n## 0x04 ~ Modifying value of a local variable given as function parameter\n\nLocal variable value are allocated on the stack, which is cleaned once you exit the function.\n\n### Useless variable change\n\n```c\nvoid increment_a(int a)\n{\n    a++; // it will have no effect\n}\n\nint solve(void)\n{\n    int a = 5;\n\n    increment_a(a);\n}\n```\n\n### Useful variable change\n\nHence if you want to modify a value you either have to use a pointer to the memory address:\n```c\nvoid increment_a(int *a)\n{\n    *a++;\n}\n\nint solve(void)\n{\n    int a = 5;\n\n    increment_a(\u0026a);\n}\n```\n\nor return the local value:\n```c\nint increment_a(int a)\n{\n    return a + 1;\n}\n\nint solve(void)\n{\n    int a = 5;\n\n    a = increment_a(a);\n}\n```\n\n## 0x05 ~ Unprotected malloc\n\nDo NOT leave a malloc unprotected:\n```c\nint allocate_memory(void)\n{\n    int *matrix;\n\n    matrix = malloc(sizeof(int) * 9))\n\n    return matrix;\n}\n\nint somefunction(void)\n{\n\tint *matrix;\n\n\tmatrix = allocate_memory();\n}\n```\n\nProtect both the malloc **and its return value**:\nIt is not good enough to protect the malloc in the callee function (the function called) if the returned value is not also protected in the caller function (the function 'above')\n```c\nint allocate_memory(void)\n{\n\tint *matrix;\n\n\tif (!(matrix = malloc(sizeof(int) * 9))) // this is short for matrix = malloc(sizeof(int) * 9; if (matrix == NULL)\n\t\treturn NULL;   // the malloc is now protected,\n\n\treturn matrix;\n}\n\nint somefunction(void)\n{\n\tint *matrix;\n\n\tif ((matrix = allocate_memory()) == NULL) // the return value is also protected\n        \texit(); // note that often you can't or don't want to use exit() and will need to return 0 along all the functions up to the main function.\n\tfree(matrix);\n}\n```\n\n---\n## 0x06 ~ Freeing memory that has already been fred\n\nIn the previous example, if you don't need the variable matrix anymore you can free it.  \n\nHowever do not attempt to free twice or to free a stack based variable:\n```c\nint main(void) {\n\tint *matrix;\n\n\tif (!(matrix = malloc(sizeof(int) * 9)))\n\t\treturn 1; // NB: exceptionnally return 1 in the main, it means that an error occured\n\tfree(matrix); // OK\n\tfree(matrix) // Not OK\n\n\treturn 0; // return 0, the program run without error\n}\n```\n\n\n---\n## 0x07 ~ Do Not use global variables\n\n\u003e \"Theory and practice sometimes clash. And when that happens, theory loses.  \nEvery single time.\" ― Linus Torvalds\n\nGlobal variables are forbidden in 42 School except for a few exceptions, see this interesting article: [Are Global Variables Bad](https://stackoverflow.com/questions/484635/are-global-variables-bad)\nHowever many students, me including, found a way to circumvent this interdiction: you first declare a structure in the header that will contain all our variables:\n\n\u003e \"Don’t comment bad code—rewrite it.\" ― *Brian W. Kernighan, The Elements of Programming Style*\n\n```c\ntypedef struct s_env\n{\n    int a;\n    int b;\n    int c[4];\n    // ... other variables you may need\n}           t_env;\n```\nAnd then using it the following way in the program:\n```c\nvoid somefunction2(t_env *env)\n{\n    env-\u003eb = 2;\n}\n\nvoid somefunction(t_env *env)\n{\n    env-\u003ea = 1;\n\n    somefunction2(env);\n}\n\nint main(void)\n{\n    t_env env;\n\n    somefunction(\u0026env);\n\n    printf(\"%d\\n\", env.a);\n    printf(\"%d\\n\", env.b);\n}\n```\n\nThis is \"legal\" in 42 (it is not a global variable, it is a structure passed along functions), it \"works\", but it is a very poor architecture choice. It is okay for beginner to do this but as your skill grows you should find more clever ways to architecture your programs.\n\n\n---\n## 0x08 ~ Variable Length Arrays\n\n[Waiter! There's a VLA in my C!](http://ayekat.ch/blog/vla)\n\nThe following example is a VLA and this is bad for many reasons, the most critical being that the memory is allocated on the stack which has a limited size.\n```c\nint somefunction(int y, int x, int array[y][x]);\n```\nMy peer reviewer: \"wow [your filler](https://github.com/agavrel/42-filler) run so fast!\"\nMe: \"really ?\" (how to tell them that it was not compliant with the norm? :D)\n\n---\n## 0x09 ~ Using ft_ prefix for all functions\n\n*ft_* should only be added to functions you want to re-use through different projects (and add to your personal library, the libft project) not for specific program functions.\n\n\n---\n## 0x0A ~ [Usage of Sequence Point](https://en.m.wikipedia.org/wiki/Sequence_point)\n```c\n#include \u003cunistd.h\u003e\n\nint main()\n{\n\tint i = 0; \n\ti = (i++);\n\twrite(1, \u0026i + '0', 1);\n\n\treturn 0;\n}\n```\nGuess what will be printed.\n\n\n---\n## 0x0B ~ Assignment of read-only location\n```c\nint main()\n{\n\tconst char s[20] = \"hello world\";\n\t*s = 'a';\n\ts[0] = 'b';\n\n\treturn 0;\n}\n```\n\nYou cannot change what you have declared as const.\n\n\n---\n## OXOC ~ Carefully use define preprocessor macros\n\n```c\n#include \u003cstdio.h\u003e\n\n#define MAX(a,b)\ta \u003e b ? a : b\n\nint main(void) {\n\tint a = 5;\n\tint b = 42;\n\tint c = 40 +  MAX(a,b);\n\t\n\tprintf(\"%d\\n\", c);\n\treturn 0;\n}\n```\n\nThis will return 5, becaure the compiler understand it as :\n```c\nint main(void) {\n\tint a = 5;\n\tint b = 42;\n\tint c = 40 + 5 \u003e 42 ? 5 : 42; // if 47 \u003e 42 then c = a (5) , else c = b (42);\n\t...\n}\n```\n\nThe correct usage is to always encapsulate your ```#define``` with brackets to make sure it works as intended:\n```c\n#define MAX(a,b)\t(a \u003e b ? a : b)\n```\n\nThat said you should avoid using macros who act like functions in the first place. Also note that you should always capitalize macro names and const variables, it is a convention.\n\n\n---\n## 0x0D ~ Comparing float and double\n\n```c\n#include \u003cstdio.h\u003e\n\nint main(void) {\n\tdouble d = 1.1;\n\tfloat f = 1.1;\n\n\tif (f != d)\n\t\tputs(\"float and double are different\\n\");\n\tif (f != 1.1)\n\t\tputs(\"Do not compare a float to an integer value\\n\");\n\tif (d == 1.1)\n\t\tputs(\"But that's okay for a double\\n\");\n\tif (f == 1.1f)  // note the extra 'f' at the end\n\t\tputs(\"This is how you compare a float to a float value\\n\");\n\n\treturn 0;\n}\n```\n\nThey are represented differently. If you want to learn more about how they work take a look at [wikipedia](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) or wach below video.  \n\n\u003ca href=\"https://www.youtube.com/watch?v=PZRI1IfStY0\" target=\"_blank\"\u003e\u003cimg src=\"http://img.youtube.com/vi/PZRI1IfStY0/0.jpg\"\nalt=\"Floating Point Numbers\" width=\"240\" height=\"180\" border=\"10\" /\u003e\u003c/a\u003e\n\n\n---\n## 0x0E ~ Wrong usage of pointers\n\nPointers are the memory location of the value of this variable\n\nAn example with ft_swap\n\n### The wrong way to use pointers\n```c\nvoid ft_swap(int *a, int *b)\n{\n\tint *tmp;\n\n\t*tmp = *a;\n\t*a = *b;\n\t*b = *tmp;\n}\n```\n\nThis will segfault, because you declared tmp as a pointer, but what you want is tmp to store the value of the memory address of a.\n\n### The correct way to use pointers\n```c\nvoid ft_swap(int *a, int *b)\n{\n\tint tmp;\n\n\ttmp = *a;\n\t*a = *b;\n\t*b = tmp;\n}\n```\n\n### Swapping without using another variable\n```c\n=void ft_swap(int *a, int *b)\n{\n\t*a ^= *b;\t\t// (1) a = a ^ b\n\t*b ^= *a;\t\t// (2) b = b ^ (a ^ b) = a\n\t*a ^= *b;\t\t// (3) a = (a ^ b) ^ a  = b  // a was set to a^b (1) and b became a (2)\n\t\n}\n```\n**NB: if you xor a number by itself you set it to 0. ```a ^= a;``` is equivalent to ```a = 0;```**  \n*If you like it you can [learn more about bitwise operations here](https://github.com/agavrel/42-Bitwise_Operators)*\n\n### Main to test above functions\n```c\n#include \u003cstdio.h\u003e\n\nint main(void)\n{\n\tint a = 5;\n\tint b = 42;\n\n\tprintf(\"a: %d \\t b: %d\\n\", a, b);\n\tft_swap(\u0026a, \u0026b);\n\tprintf(\"a: %d \\t b: %d\\n\", a, b);\n\treturn 0;\n}\n```\n\n---\n## 0x0F ~ Undefined Behavior\n\nUndefined behavior means that the result is **as much unpredictable as a [pangolin](https://en.wikipedia.org/wiki/Pangolin) sneezing in some faraway country**. *You don't want to have your program depending on it.*\n\n```c\n#include \u003cstdio.h\u003e\n\nchar omg(char i) {\nreturn ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i + ++i \\\n \t+ ++i + ++i + ++i + ++i + ++i + ++i -5;\n}\n\n\nint main(int argc, char **argv) {\n\tunsigned char i = omg(i);\n\n\tif (i++ \u003e 254)\n\t\tprintf(\"%d\\n\", ++i);\n}\n```\n*Try guessing the output*\n\n\n---\n## 0x10 ~ Operator Precedence\n\nOften you may write some code like:\n```c\nreturn !(a \u0026 b \u003c\u003c 8);\n```\n\nThis is bad because you ignore the rule of operator precedences, and should have written the return as:\n```c\nreturn !(a \u0026 (b \u003c\u003c 8));\n```\n\nAnother example with pointers:\n```c\n*s-\u003ea++;\n(*s)-\u003ea++;\n(*s-\u003ea)++;\n```\n\nBelow you will find the full table of [operator precedence](https://en.cppreference.com/w/c/language/operator_precedence):\n\nPrecedence | Operator | Description | Associativity\n---|---|---|---\n1|++ --|\tSuffix/postfix increment and decrement|Left-to-right\n1|()|Function call|Left-to-right\n1|[]|Array subscripting|Left-to-right\n1|.|Structure and union member access|Left-to-right\n1|-\u003e|Structure and union member access through pointer|Left-to-right\n1|(type){list}|Compound literal(C99)|Left-to-right\n2|++ --|Prefix increment and decrement|Right-to-left\n2|+ -|\tUnary plus and minus|Right-to-left\n2|! ~|\tLogical NOT and bitwise NOT|Right-to-left\n2|(type)|Cast|Right-to-left\n2|*|\tIndirection (dereference)|Right-to-left\n2|\u0026|\tAddress-of|Right-to-left\n2|sizeof|Size-of|Right-to-left\n2|_Alignof|Alignment requirement(C11)|Right-to-left\n3|* / %||Left-to-right\n4|+ -||Left-to-right\n5|\u003c\u003c \u003e\u003e||Left-to-right\n6|\u003c \u003c=||Left-to-right\n7|\u003e \u003e=||Left-to-right\n8|== !=||Left-to-right\n9|\u0026||Left-to-right\n10||Bitwise OR|Left-to-right\n11||Logical AND|Left-to-right\n12|\\|\\||logical OR|Left-to-right\n13|?:|Ternary conditional|Right-to-left\n14|\t=|Assigment|Right-to-left\n14|+= -=|Assigment by sum and difference|Right-to-left\n14|*= /= %=|Assigment by product, quotient and remainder|Right-to-left\n14|\u003c\u003c= \u003e\u003e=|Assigment by bitwise left and right shift|Right-to-left\n14|\u0026= ^= |=|Assigment by bitwise AND, XOR and OR|Right-to-left\n15|,|Comma|Left-to-right\n\n\n---\n\n## Conclusion: Condensed version of mistakes that still compile\n\nA full example of a program compiling but that will not work as intended:\n\n```c\n#include \u003cstdio.h\u003e // notably for printf\n#include \u003cstdlib.h\u003e // notably for malloc\n\nvoid increment(int n);\nint *create_and_print_int_array(int len);\n\nint main(void) {\n\n/* float and double are different */\n    float f = 1.54321; // should be 1.54321f to assign a float value\n    double d = 1.54321;\n    if (f == d) // float and double are represented differently\n        printf(\"true\");\n\n\n/* always initialize your variables */\n    int i;\n    printf(\"%d\\n\", i); // by default C value are not initialized to 0;\n\n\n/* changing a variable value */\n    i = 2; // you can set a variable value with an assignation\n    increment(i); // either give the variable's address by passing the pointer, or returning a new value from the function.\n    i++;\n    printf(\"%f\\n\", i); // use printf with the correct format specifier, f is for double and float, while d is for integers.\n    printf(\"%d\\n\", i); // that's much better\n\n\n/* know the range of each type */\n    char c = 'a';\n    while (c \u003c 150) // what is c type? what is c type's max value?\n        c++;\n\n    int n = -2147483648; // INT_MIN value;\n    n = -n; // should print 2147483648 right?\n    printf(\"%d\\n\", n);\n\n    unsigned int m = 0xffffffff; // unsigned int max value is easily represented with 8 'f' (2 'f' = 1 byte)\n    unsigned int l = (1 \u003c\u003c 32) - 1; // will overflow, you have to write (1UL \u003c\u003c 32)\n    printf(\"m: %u\\nl: %u\\n\", m, l);\n\n    n = 0;\n    while (--n) // not as secured as writing while (--n \u003e= 0)\n        printf(\"%d\\n\", n);\n\n    m = 5;\n    while (m --\u003e -1) // will always be true as unsigned are always equal to 0 or superior\n        printf(\"%d\\n\", m); // should be %u for unsigned\n\n/* about using malloc */\n    int *arr;\n    arr = create_and_print_int_array(5);\n\n\n/* about using correctly scanf */\n    int a;\n    scanf(\"%d\", a); // scanf takes a pointer, you have to add \u0026\n}\n\n// wrong way to change a variable's value:\nvoid increment(int n) {\n    n += 1; // the local value of n is modified, also it can be written as ++n; or n++;\n}\n\n// correct ways to change a variable's value:\nvoid increment_using_ptr(int *i) { // increment_using_ptr(\u0026i);\n    *i++;\n}\n\nint increment_using_return(int i) { // i = increment_using_return(i);\n    return i + 1;\n}\n\n// malloc correctly and protect it\nint *create_int_array(int len) {\n    int *n;\n    n = (int *)malloc(len); // there are three things wrong:\n    // 1: there is no need to cast the result of malloc\n    // 2: you should actually malloc sizeof(int) * len, as you give to malloc a number of bytes to malloc, but integer is stored on 4 bytes\n    // 3: malloc can fail, so it should be protected:\n    /*if (n == NULL)\n        return NULL;*/\n    return n;\n}\n\nint *create_and_print_int_array(int len) {\n    int *n = create_int_array(len); // if the memory allocation from the subfunction fails, no protection, should add if (n == NULL) below\n    /*if (n == NULL)\n        return NULL;*/\n    n[5] = 5; // n[5] is equivalent to *(n + 5), problem: we have only (intended to) malloc 5 items, not 6.\n    for (int i = 0; i \u003c= len; i++) // index rightfully starts at 0 but should end at len - 1. Also sizeof(n) is not equivalent to len.\n        printf(\"%d \", n[i]); // it can still work but it is undefined behavior.\n    printf(\"\\n\");\n    return n;\n}\n```\n\n\n---\n# :snowflake: Clean Code\n\n\u003e \"You are reading this book for two reasons. First, you are a programmer. Second, you want to be a better programmer. Good. We need better programmers.\" ― *Robert C. Martin in Clean Code*\n\nNow some guidelines that should hopefully help your coding style\n\n\n---\n## 0x00 ~ Meaningful and Explicit Names\n\n\u003e \"The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly.\" - \nDonald Ervin Knuth\n\nI once met a developer who was using hp and mp instead of x and y for coordinates.  \nWhile being a very good reference to [JRPG]()... it is totally out of question to code like this.\nThe function name should always be:\n* In English, forget about chauvinism!\n* At least 5 letters. It is okay to have shorter exceptionally for well-known variables like int index -\u003e int i, temporary -\u003e tmp and pointer -\u003e ptr.\n* Self-explanatory: build_graph instead of graph or build_it\n* For long name use either camel case (saveClientConfig) or snake case (save_client_config) and stick to one style.\n\n### Writing a function check if a file exist\n\n```c\n#include \u003csys/stat.h\u003e\t// stat\n#include \u003cstdbool.h\u003e \t// bool type\n#include \u003cstdio.h\u003e\t\t// printf\n\nbool\tfile_exist (char *filename)\t// Always use bool for Manichean functions\n{\n  struct stat   buffer;\n\n  return !stat(filename, \u0026buffer);\n}\n\nint\t\tmain(int ac, char **av) {\n\tif (ac != 2)\n\t\treturn 1;\n\n\tif (file_exist(\"a.out\"))\n\t\tprintf(\"%s exists\\n\", av[1]);\n\telse\n\t\tprintf(\"%s does not exist\\n\", av[1]);\n\n\treturn 0;\n}\n```\n\n\n---\n## 0x01 ~ Write short functions\n\n\u003e \"FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.\" ― *Robert C. Martin in Clean Code (p35)*\n\n**42 has a rigid but fair rule: limits every functions to 25 lines.**  \n\n*Let's see a case study with a function to get lower case (from 'A' to 'a') for a given character*\n\n**0b001 Function done by a 42 'Piscineux' (AKA it works):**\n```c\nchar\tto_lower_by_piscineux(char c) {\n\tif (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z')\n\t\treturn c - 'A' + 'a';\n\telse if (c \u003e= 'a' \u0026\u0026 c \u003c= 'a')\t// useless else if, since both else if and else return the same value\n\t\treturn c;\n\telse\n\t\treturn c;\n}\n```\n\n**0b010 Good 42 Student who read GNU C library's tolower's man and read ```int tolower(int c)``` (prototype):**\n```c\nint\t\tto_lower_by_student(int c) {\n\tif (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z')\n\t\treturn c - 'A' + 'a';\n\telse\t\t\t// NB: Don't keep this extra \"else\" as there is no code executed after the return statement\n\t\treturn c;\n}\n```\n\n**0b011 However you could save memory by using only 1 byte (char) instead of 4 (int) since ASCII values range from 0 to 127 as demonstrated by Steve Maguire in \"Writing Solid Code\" (p101):**\n```c\nchar\tto_lower_by_smaguire(char c) {\n\tif (c \u003e= 'A' \u0026\u0026 c \u003c= 'Z')\n\t\treturn (c + 'a' - 'A');\n\treturn (c);\n}\n```\n\n**0b100 My own version: [making use of the ASCII table](https://en.wikipedia.org/wiki/ASCII) and apply the Do Only One Thing principle:**\n```c\n#include \u003cstdbool.h\u003e    // bool type\n\nbool\tis_upper_case(int c) {\n\treturn ((unsigned int)(c - 'A') \u003c= ('Z' - 'A'));\n}\n\nint\t\tto_lower_by_agavrel(int c) {\t\t// Check ASCII table and you will notice a nice pattern\n\treturn is_upper_case(c) ? c | 0b100000 : c;\n}\n```\n\n**0b101 You may try above functions with the following main program:**\n```c\n#include \u003cunistd.h\u003e\t\t// write syscall\n\nvoid\tputchar_endl(char c) {\t// NB: endl stands for endline, '\\n'\n\twrite(1, \u0026c, 1);\n\twrite(1, \"\\n\", 1);\n}\n\n#include \u003cctype.h\u003e \t\t// GNU C Library tolower\n\nint\t\tmain(int ac, char **av) {\n\tif (ac != 2)\n\t\treturn 1;\n\n\tunsigned char c = *av[1];\n\tputchar_endl(tolower(c));\n\tputchar_endl(to_lower_by_piscineux(c));\n\tputchar_endl(to_lower_by_student(c));\n\tputchar_endl(to_lower_by_smaguire(c));\n\tputchar_endl(to_lower_by_agavrel(c));\n\n\treturn 0;\n}\n```\n\n**0b110 Have you tried [one step closer](https://www.youtube.com/watch?v=kSUsBpdugX0) to the bytecode  ?**\n```c\nint\t\tto_lower_assembly(int c) {\n\t__asm__ __volatile__ (R\"(\n\t.intel_syntax noprefix\n\t\tmov     eax, %0\n        lea\t\tedx, [eax - ('A')]\n\t\tor      %0, 0b100000\n\t\tcmp\t\tedx, 'Z'-'A'\n        cmovb\teax, %0\t\t\n\t.att_syntax noprefix)\"\n\t:[c]\"=r\" (c)\n\t:: \"memory\");\n}\n```\n\n\n---\n## 0x02 ~ Using structure for basic items\n\nIf you are using coordinates it might be interesting to create a structure 'point' or 'coord'\n\n```c\ntypedef struct s_point\n{\n    int y;\n    int x;\n}           t_point;\n\nvoid somefunction(void){\n    t_point p;\n\n    p.x = 2;\n    p.y = 5;\n\n    //alternatively:  p = {5, 2};\n}\n```\n\n\n---\n## 0x03 ~ Using flags for projects' options\n\nFor each project you will often have to parse flag input. In Linux the flag usually come after a '-' and allow for extra functionalities.\nIt is quite useful know how to store such critical information into only 4 bytes *which is sizeof(integer)*\n\n```c\nstatic int\tft_strchr_index(char *s, int c)\n{\n\tint\t\ti;\n\n\ti = 0;\n\twhile (s[i])\n\t{\n\t\tif (s[i] == c)\n\t\t\treturn (i);\n\t\t++i;\n\t}\n\treturn (-1);\n}\n\nint\t\t\tget_flags(char *s, int *flags)\n{\n\tint\t\tn;\n\n\twhile (*(++s))\n\t{\n\t\tif ((n = ft_strchr_index(\"alRrtdG1Ss\", *s)) == -1)\n\t\t\treturn (0);\n\t\t*flags |= (1 \u003c\u003c n);\n\t}\n\treturn (1);\n}\n\nint\t\t\tmain(int ac, char **av)\n{\n\tint\ti;\n\n\tint flags = 0;\n\ti = 0;\n\twhile (++i \u003c ac \u0026\u0026 av[i][0] == '-' \u0026\u0026 av[i][1])\n\t{\n\t\tif (av[i][1] == '-' \u0026\u0026 av[i][2])\n\t\t\treturn (i + 1);\n\t\tif (!get_flags(av[i], \u0026flags))\n\t\t\treturn (-1);\n\t}\n\treturn (i);\n}\n```\n\nThe 'a' flag will be on bit 1, 'l' on bit 2, 'R' on bit 4, 'r' on bit 8 etc.\nYou can then test if the flag was on by using the following:\n```c\n#define FLAG_A  0b001\n#define FLAG_L  0b010\n#define FLAG_RR 0b100\n\n#include \u003cstdio.h\u003e\n\nvoid    somefunction(int *flags)\n{\n\tif (flags \u0026 FLAG_A)\n\t\tprintf(\"Flag a is set!\\n\");    \n}\n```\n\n*NB: Be very cautious as \u0026 and | have lower precedence than relational operators:*\n```c\nif (flags \u0026 FLAG_L == MASK) // equivalent to (flags \u0026 (FLAG_L == MASK))\n```\n\n*Correct example:*\n```c\nif ((flags \u0026 FLAG_L) == MASK)\n```\n\nYou can unset a flag by clearing the corresponding bit the following way:\n```c\nvoid    somefunction2(int *flags)\n{\n\tflags \u0026= ~FLAG_A;\n}\n```\n\n\u003e **Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live** – *John Woods*\n\nAn even more readable and better approach is to declare a struct using bitfield:\n\n```c\nstruct \tflags_t\n{\n\tint a : 1;\n\tint b : 1;\n\tint c : 1;\n\t//etc\n}\n\n#include \u003cunistd.h\u003e\n\nint\tmain(void) {\n\tstruct flags_t flags = {0};\n\tflags.a = 1;\n\tif (flags.a)\n\t\twrite(1, \"flag a is set\\n\", 14);\n\treturn 0;\n}\n```\nPS: Of course rename flags' name with more meaningful ones.\n\n\n---\n## 0x04 ~ Using gcc flags for Makefile\n\n\u003e **It's funny how the smallest things I've done speak the loudest about me, but I like that** ― *Xavier Niel*\n\n```\ngcc -Wall -Wextra -Werror -O2\n```\n* O2 will improve performance  ##Create a new repository on the command line\n* pedantic is not requested but is a good one to check ISO C compliance\n\n\u003e Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and some other programs that do not follow ISO C and ISO C++. For ISO C, follows the version of the ISO C standard specified by any -std option used.\n\nYou can read the details about each flag on [gccgnu website](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html)\n\n\n---\n## 0x05 ~ Using preprocessor DEBUG macros\n\n\u003e **Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?** ― *Brian W. Kernighan*\n\nYou can improve the performance of your program by using what we call preprocessor macros\n```c\n#include \u003cunistd.h\u003e\n\n#define DEBUG true\n\nint main(void) {\n\tif (DEBUG)\n\t\twrite(1, 42, 1);\n\treturn 0;\n}\n```\nAs a convention name should be capitalized with '_' to join words\n\n---\n## 0x06 ~ Branching Optimization\n\nOften you will test that a specific value is reached or that a variable is set using if condition. But the order of the comparisons can improve efficiency of your program.  \n\nWhat would be wrong with the below function?\n```c\n\nint counter_to_star(int a, int b) {\n\twhile (42) {\n\t\tif (((a + b) \u0026 1) \u0026\u0026 a == 42) {\n\t\t\tbreak;\n\t\t}\n\t\ta |= 1;\n\t\ta *= b;\n\t\ta %= 60;\n\t\tb++;\n\t\tn++;\n\t}\n\n\treturn n;\n}\n```\n\nWhat is wrong is that the most unlikely condition ```a == 42``` is tested last, while it should be tested first. The most likely condition, that a + b is odd ```(a + b) \u0026 1``` should be tested only if a == 42, and since 42 is even, you only need to test if b is odd:\n```\nif (a == 42 \u0026\u0026 (b \u0026 1)) {\n\tbreak;\n```\n\n\n```\n#include \u003cunistd.h\u003e\n\n#define DEBUG true\n\nint main(void) {\n\tint a = 42;\n\tif (a \u0026\u0026 a \u003c)\n\treturn 0;\n}\n```\n\n---\n## 0x07 ~ Reserved Keywords\n\n\u003e \"Don’t comment bad code, rewrite it.\" - Brian W. Kernighan, The Elements of Programming Style\n\nKeyword | Meaning\n---|---\n**static** | *the function or variable can only be used within its file, it is somewhat similar to the concept of private*\n**inline** | *compiler will attempt to embed the function into the calling code instead of executing an actual call.*\n**const** | *will make the variable immutable* \n**break; continue;** | *will respectively exit from the loop and go to the beginning of the loop*\n\n\n---\n# Programmer Tools\n\n---\n## 0x00 ~ Code Editors\n\n### Vim, Code Editor used in 42\n\nVIM is the text editor used in 42. You access a file by using ```vim filename```. To exit VIM  with elegance vim type ```:q```, if you fail to exit VIM you might consider becoming a freelance web developer.\n\n\u003e To generate a truly random string, put a web developer in front of Vim and tell them to exit\n\nYou can access VIM configuration by typing\n```\nvim ~/.vimrc\n```\n\nBelow is my configuration\n```\nset number\t\t\t\t\t\t\t\" Show line number\nsyntax on\t\t\t\t\t\t\t\" Highlight syntax\nset mouse=r\t\t\t\t\t\t\t\" Enable mouse click, + enable to copy paste without taking line number\nset cursorline\t\t\t\t\t\t\" Enables cursor line position tracking\nhi Normal guibg=NONE ctermbg=NONE\t\" keep vim transparency\nhighlight CursorLine ctermfg=darkgreen ctermbg=darkgrey cterm=bold\t\" highlight row with foreground background and style as defined\n\"highlight CursorColumn ctermbg=darkgrey\t\t\t\t\t\t\t\t\" hilight column\nhighlight CursorLineNR ctermfg=red ctermbg=darkblue cterm=bold\t\" Sets the line numbering to red background\n\nset cursorcolumn \t\t\t\t\t\" Highlight current column\nset tabstop=4\t\t\t\t\t\t\" set tab to 4 spaces\nset autoindent\t\t\t\t\t\t\" auto indent file on save\n\nset modeline\t\t\t\t\" make vim change in a specific file\nset modelines=5\n```\n\nSome shortcuts that are very handy:\n```\nCTRL+HOME\tsend you at the beginning of the file\nCTRL+END\tsend you at the end of the file\nYY\t\t\tcopy\nPP\t\t\tpaste\nDD\t\t\tdelete row\nD5D\t\t\tdelete 5 rows\nw\t\t\tsave file\nq\t\t\tquit file\n:vs {file location}\t\topen another file on the side\n:ws\t\t\tsave and quit\nZZ\t\t\tsave and quit\n:x\t\t\tsave and quit\n:q!\t\t\tquit without change\nZQ\t\t\tquit without change\n```\n\n### Visual Studio Code\n\nI love VIM and it will always be useful to know how to use it, especially now with the \"Cloud\" being something you might have to access servers who lack code editors with real GUI.\n\nThat said If you want to give a try to another editor I would recommend Visual Studio Code.\n\nMy settings.json:\n```\n{\n    \"workbench.colorTheme\": \"Monokai\",\n    \"glassit-linux.opacity\": 93\n}\n```\n\n### Atom\n\nGood editor also, quite hackable, I have been using it for years but recently switch to VIM \u0026 VS Code\n\n\n---\n## 0x01 ~ Terminal Bash\n\n[Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) is the terminal you will be using\n\nYou can create alias by accessing\n```\nvim ~/.bashrc\n```\n\n```\nalias ls=\"ls -la\"\n```\n\nPS: Don't create this alias on another's student computer, even thought you might think it is funny, it will wipe out everything:\n```\nalias ls=\"rm -rf ./~\"\n```\n\n\n---\n## 0x02 ~ Git\n\n### Setting up a new Git Repository using [CLI](https://en.wikipedia.org/wiki/Command-line_interface)\n\nIt can be done easily using the following command line:  \n```\nreponame='docker'\nmkdir $reponame\ntouch README.md\ngit init\ngit add README.md\ngit commit -m \"[INIT] First commit\"\ngit remote add origin git@github.com:agavrel/$reponame.git\ngit push -u origin master\n```\n\n### Change last commit without changing commit message\n\n\u003e **I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it** ― *Bill Gates*\n\nIt can be done easily using the following command line\n```\ngit add README.md \\\n\u0026\u0026 git commit --amend --no-edit \\\n\u0026\u0026 git push --force\n```\n**NB: Beware because it will destroy the previous commit with all what it implies**\n\n\n### Check file committed and unpushed yet\n\n```\ngit diff --stat --cached origin/master\n```\n\n### Undo git add\n\n```\ngit reset \u003cfile\u003e\n```\n\n\n---\n## 0x03 ~ Productivity Gains \n\n\u003e **One of my most productive days was throwing away 1000 lines of code** ― *[Ken Thompson](https://en.wikipedia.org/wiki/Ken_Thompson)*\n\n### [Compile and Execute file on changes](https://superuser.com/questions/181517/how-to-execute-a-command-whenever-a-file-changes?page=2\u0026tab=votes#tab-top)\n\nCreate ou run the following script (necessite to download ```sudo apt-get install inotifywait```)\n```\nwhile inotifywait -e close_write agavrel.s; do \\\nnasm -f elf64 agavrel.s \\\n\u0026\u0026 gcc agavrel.c agavrel.o -o a.out \\\n\u0026\u0026 ./a.out arg1 arg2 \\\n; done\n```\nNow each time you compile your file you will set the output, very efficient with a transparent editor.\n\n**Use the following script and give the .c file as argument:**\n```\nwhile inotifywait -e close_write $1; do \\\ngcc $1 \\\n\u0026\u0026 ./a.out \\\n; done\n```\n\n---\n### [Run Commands in Background](https://linuxize.com/post/how-to-run-linux-commands-in-background/)\n\nYou can have multiple processes running in the background at the same time with ```\u0026``` after the command.  \nHowever the background process will continue to write messages to the terminal from which you invoked the command.  \n\nTo suppress the stdout and stderr messages use the following syntax:  \n```\ncommand \u003e /dev/null 2\u003e\u00261 \u0026\n```\n\n```\u003e/dev/null 2\u003e\u00261``` means redirect ```stdout``` to ```/dev/null``` and ```stderr``` to ```stdout```\n\nUse the jobs utility to display the status of all stopped and background jobs in the current shell session:\n```\njobs -l\n```\n_NB: a Job is the process running thanks to the command execution_\n\nTo bring the job to the foreground use :\n```\nfg %ID\n```\nNB: you can use ```bg``` to do the reverse, from foreground to background.\n\nTo kill the process use:\n```\nkill -9 ID\n```\nObviously replace ```ID``` in the above examples with the job ID you got from ```jobs -l```.\n\n\n---\n\n### Read first 8 bytes of a file\n\n```\nhexdump -C -n 8 filename\n```\n\n\n---\n## 0x04 ~ [Add a a new binary in the PATH environment variable](https://stackoverflow.com/questions/14637979/how-to-permanently-set-path-on-linux-unix)\n\nExample with terraform:\n```\nsudo mkdir /opt/terraform\nunzip ~/Downloads/terraform_0.12.13_linux_amd64.zip /opt/terraform\n```\n\nadd to PATH environment variable:\n```\nexport PATH=\"$PATH:/opt/terraform\"\n```\n\nthen create simlink in /user/bin\n```\ncd /usr/bin\nsudo ln -s /opt/terraform terraform\n```\n\nUpdate path for current session\n```\nsource ~/.profile\n```\nor\n```\nsource ~/.bashrc\n```\n\n\n---\n## 0x05 ~ Computer Graphics Libraries (Ubuntu)\n\n#### Minilibx Installation\n\nLink\n```\nhttps://github.com/42Paris/minilibx-linux\n```\n\n### SDL2 Installation\n\nLink\n```\nhttp://www.libsdl.org/download-2.0.php#source\n```\n\nThen\n```\n./configure\n\u0026\u0026 make\n\u0026\u0026 sudo make install\n\u0026\u0026 sudo apt-get install ibsdl2-dev libsdl2-ttf-dev\n\u0026\u0026 sudo apt-get libsdl2-image-2.0-0 libsdl2-image-dev\n```\n\n\n---\n# :gem: Curated list of Programming Learning Materials\n\n*Only petty thieves would google the following material, adding \"torrent\" or \"pdf\" keywords, real Gentlemen would purchase a digital copy*  \n\n**NB: If you want to complain about a copyright enfringment, kindly raise an issue or send me an email and I will remove the offending link**  \n\n---\n## 0x00 ~ C Knowledge\n\n```c\n#include \u003cstdio.h\u003e\n\nint f(int n) {*\u0026n*=2;}\n\nint main(void) {\n    printf(\"%d\\n\", f(0b10101));\n}\n```\n\n\u003e **C is [quirky](https://en.wiktionary.org/wiki/quirky), flawed, and an enormous success** ― *[Dennis Ritchie, Creator of the C language](https://en.wikipedia.org/wiki/Dennis_Ritchie)*\n\nTitle | How Interesting | Author\n---|---|---\n**[The C Programming Language 2nd Ed Subsequent Edition](https://www.goodreads.com/book/show/515601.The_C_Programming_Language)** | :two_hearts: | *by Brian Kernighan and Dennis Ritchie*\n**[Obscure C Features](https://multun.net/obscure-c-features.html)** | :star::star::star::star::star: | *[by Multun](https://github.com/multun)*\n**[Characters, Symbols and the UTF-8 Miracle - Computerphile](https://www.youtube.com/watch?v=MijmeoH9LT4)** | :star::star::star::star: | *by Tom Scott*\n**[Automatic Vectorization](https://www.codingame.com/playgrounds/283/sse-avx-vectorization/autovectorization)** | :star::star::star::star: | *[by Marchete](https://github.com/marchete)*\n**[Writing Solid Code](http://cs.brown.edu/courses/cs190/2008/documents/restricted/Writing%20Solid%20Code.pdf)** | :star::star::star::star: | *by Steve Maguire*\n**[Fast wc Multithread SIMD](https://github.com/expr-fi/fastlwc)** | :star::star::star::star: | *by [expr-fi](https://github.com/expr-fi)*\n**[OpenMP Multithreading Programming](https://bisqwit.iki.fi/story/howto/openmp/)** | :star::star::star::star: | *by Joel Yliluoma*\n**[Understanding lvalues and rvalues](https://eli.thegreenplace.net/2011/12/15/understanding-lvalues-and-rvalues-in-c-and-c/)** | :star::star::star::star: | *by Eli Bendersky*\n**[The Practice of Programing](http://index-of.co.uk/Etc/The.Practice.of.Programming.-.B.W..Kernighan..pdf)** | :star::star::star: | *by Brian W. Kernighan and Rob Pike*\n**[Modern C](https://gforge.inria.fr/frs/download.php/file/38170/ModernC.pdf)** | :star::star::star: | *by Jens Gustedt*\n**[Duff's Device](http://www.lysator.liu.se/c/duffs-device.html)** | :star::star::star: | *by Tom Duff*\n**[Structure Packing](http://www.catb.org/esr/structure-packing/)** | :star::star::star: | *by Eric S. Raymond*\n**[Cello, High Level Programming to C](https://github.com/orangeduck/Cello)** | :star::star::star: | *by Daniel Holden*\n**[Asynchronous Routines for C](https://hackaday.com/2019/09/24/asynchronous-routines-for-c/)** | :star::star::star | *by AI William*\n**[Are Global Variables Bad](https://stackoverflow.com/questions/484635/are-global-variables-bad)** | :star: | *StackOverFlow*\n\n\n---\n## 0x01 ~ Algorithm\n\n\u003e **When you see a good move, look for a better one** ― *[Emanuel Lasker](https://en.wikipedia.org/wiki/Emanuel_Lasker)*\n\nTitle | How Interesting | Author\n---|---|---\n**[Nailing the Coding Interview](https://github.com/agavrel/Nailing-the-Coding-Interview)** | :kr: | *by Antonin Gavrel*\n**[A curated list of Awesome Competitive Programming](https://codeforces.com/blog/entry/23054)** | :star::star::star::star: | *by Inishan (Jasmine Chen)*\n**[The Algorithm Design Manual](https://www.goodreads.com/book/show/425208.The_Algorithm_Design_Manual)** | :star::star::star::star: | *by Steven S. Skiena*\n**[Games of Magnus Carlsen and Tactics, 2013](https://www.youtube.com/watch?v=Na9g-RzSLuY\u0026t=8m35s)** | :star::star::star::star: | *by [GM Varuzhan Akobian](https://en.wikipedia.org/wiki/Varuzhan_Akobian)*\n**[A tour of the top 5 sorting algorithms with Python code](https://medium.com/@george.seif94/a-tour-of-the-top-5-sorting-algorithms-with-python-code-43ea9aa02889)** | :star::star: | *by George Seif*\n\n\u003e **Strategy requires thought, tactics require observation** ― *[Max Euwe](https://en.wikipedia.org/wiki/Max_Euwe)*\n\n\n---\n## 0x02 ~ Bitwise Manipulations\n\n\u003e **The word bit is a contraction of binary digit that was coined by the statistician John Tukey in the mid 1940s** ― *Brian W. Kernighan, D Is for Digital*\n\nTitle | How Interesting | Author\n---|---|---\n**[Hacker's Delight](https://doc.lagout.org/security/Hackers%20Delight.pdf)** | :two_hearts: | *by Henry S. Warren Jr.*\n**[Bit Twiddling Hacks](https://graphics.stanford.edu/~seander/bithacks.html)** | :two_hearts: | *by Sean Eron Anderson*\n**[De Bruijn Sequence](https://www.chessprogramming.org/De_Bruijn_Sequence)** | :star::star:\n\n\n---\n## 0x03 ~ Network\n\n\u003e **I would tell you a joke about UDP but I’m afraid you wouldn’t get it**\n\nTitle | How Interesting | Author\n---|---|---\n**[Next Generation Kernel Network Tunnel - WireGuard](https://www.wireguard.com/papers/wireguard.pdf)** | :two_hearts: | by JA Donenfeld |\n**[Onion Routing](https://www.youtube.com/watch?v=QRYzre4bf7I)** | :star::star::star::star: | *by Computerphile*\n**[TCP Meltdown](https://www.youtube.com/watch?v=AAssk2N_oPk)** | :star::star: | *by Computerphile*\n\n\n---\n## 0x04 ~ Hacking \u0026 Security\n\n\u003e **Never underestimate the determination of a kid who is time-rich and cash-poor** ― *Cory Doctorow, Little Brother*\n\nTitle | How Interesting | Author\n---|---|---\n**[Smashing The Stack For Fun And Profit](http://www-inst.eecs.berkeley.edu/~cs161/fa08/papers/stack_smashing.pdf)** | :two_hearts: | *by Aleph One*\n**[Violent Python - A Cookbook for Hackers, FA, PT and SE](https://repo.zenk-security.com/Programmation/Violent%20Python%20-%20A%20Cookbook%20for%20Hackers,%20Forensic%20Analysts,%20Penetration%20Testers%20and%20Security%20Enginners.pdf)** | :two_heats: | *by TJ O'Connor*\n**[Breaking the x86 Instruction Set](https://www.youtube.com/watch?v=KrksBdWcZgQ)** | :star::star::star::star::star: | *[by Domas](https://github.com/xoreaxeaxeax)*\n**[Buffer Overflow, Race Condition, Input Validation, Format String](http://www.cis.syr.edu/~wedu/Teaching/cis643/schedule.html)** | :star::star::star::star: | *by Wenliang (Kevin) Du*\n**[Meltdown](https://meltdownattack.com/meltdown.pdf)** | :star::star::star::star: | *by Lipp, Schwarz, Gruss, Prescher, Haas, Mangard, Kocher, Genkin, Yarom, and Hamburg*\n**[Basic Linux Privilege Esclation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/)** | :star::star::star: | *by g0tmi1k* \n**[Network Protocol Fuzzing and Buffer Overflow](https://blog.own.sh/introduction-to-network-protocol-fuzzing-buffer-overflow-exploitation/) | :star::star::star::star: | *by Joey Lane*\n**[Secure Programming HOWTO](https://dwheeler.com/secure-programs/Secure-Programs-HOWTO.pdf)** | :star::star::star: | *by David A. Wheeler*\n**[Padding the struct](https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2019/october/padding-the-struct-how-a-compiler-optimization-can-disclose-stack-memory/)** | :star::star::star: | by *NCC Group*\n**[Efficiently Generating Python Hash Collisions](https://www.leeholmes.com/blog/2019/07/23/efficiently-generating-python-hash-collisions/)** | :star::star:\n**[Stochastic Process Wikipedia](https://en.wikipedia.org/wiki/Stochastic_process)** | :star::star:\n**[Gimli: a cross-platform permutation](https://eprint.iacr.org/2017/630.pdf)** | :star::star:\n**[LiveOverflow](https://www.youtube.com/channel/UClcE-kVhqyiHCcjYwcpfj9w)** | :star::star:\n\n\u003cdetails\u003e\n\n\u003csummary\u003e*p/q2-q4*\u003c/summary\u003e\n\n**[Forum cracks the vintage passwords of Ken Thompson and other Unix pioneers](https://arstechnica.com/information-technology/2019/10/forum-cracks-the-vintage-passwords-of-ken-thompson-and-other-unix-pioneers/)**  \n**[Most Common Chess Openings](https://www.thesprucecrafts.com/most-common-chess-openings-611517)**  \n**[Kasparov Miniature and Tactics/Endgames | Kids' Class - GM Varuzhan Akobian](https://www.youtube.com/watch?v=_B39II74Pkc)**  \n\n\u003c/details\u003e\n\n\u003e **When in doubt, use bruteforce** ― *[Ken Thompson](https://en.wikipedia.org/wiki/Ken_Thompson)*\n\n\n---\n## 0x05 ~ Computer Graphics\n\n\u003e **Programming is not a zero-sum game. Teaching something to a fellow programmer doesn't take it away from you. I'm happy to share what I can, because I'm in it for the love of programming** ― *[John Carmack](https://en.wikipedia.org/wiki/John_Carmack)*\n\nTitle | How Interesting | Author\n---|---|---\n**[SDL2 Tutorial](https://lazyfoo.net/tutorials/SDL/01_hello_SDL/linux/index.php)** | :two_hearts: | *by mysterious Lazyfoo*\n**[The Book of Shaders](https://thebookofshaders.com/01/)** | :two_hearts: | *by Patricio Gonzalez Vivo \u0026 Jen Lowe*\n**[Fast Inverse Square Root](https://en.wikipedia.org/wiki/Fast_inverse_square_root)** | :two_hearts: | attributed to John Carmack (Quake III)\n**[Game Engine Architecture](http://ce.eng.usc.ac.ir/files/1511334027376.pdf)** | :star::star::star::star::star: | *by Jason Gregory*\n**[Introduction to Computer Graphics](https://www.youtube.com/watch?v=t7g2oaNs-c8\u0026list=PLQ3UicqQtfNuKZjdA3fY1_X9gXn13JLlW\u0026index=1)** | :star::star::star::star::star: | *by Justin Solomon*\n**[RayCasting Tutorial + Source Code](https://lodev.org/cgtutor/raycasting.html)** | :star::star::star::star::star: | *by Lodev*\n**[Shaders Programming](https://www.hiteshsahu.com/blogs)** | :star::star::star::star: | *by [Hitesh Sahu](https://github.com/hiteshsahu)*\n**[Coding Minecraft in two days](https://youtu.be/4O0_-1NaWnY)** *(source code)[https://github.com/jdah/minecraft-weekend]* | :star::star::star::star::star: | *by [Jdah](https://github.com/jdah)*\n**|[Moving Frostbite to Physically Based Rendering 3.0](https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf)** | :star::star::star::star: | *by Sebastien Lagarde and Charles de Rousiers*\n**[3d Fractal Flame Wisps](https://tigerprints.clemson.edu/cgi/viewcontent.cgi?article=2704\u0026context=all_theses)** | :star::star::star: | *by [Yujie Shu](https://www.semanticscholar.org/author/Yujie-Shu/11523322)*\n**[Geometry Caching Optimizations in Halo 5](https://www.youtube.com/watch?v=uYAjUOlEgwI)** | :star::star::star: | *by Zabir Hoque and Ben Laidlaw*\n**[Physically-Based Shading at Disney](https://disney-animation.s3.amazonaws.com/library/s2012_pbs_disney_brdf_notes_v2.pdf)** | :star::star::star: | *by Brent Burley, Walt Disney Animation Studios*\n**[Light and Shadows in Graphics](https://www.youtube.com/watch?v=LUjXAoP5GG0)** | :star::star: | *by Tom Scott*\n**[Screen Space Ambient Occlusion Tutorial](http://john-chapman-graphics.blogspot.com/2013/01/ssao-tutorial.html)** | :star::star: | *by Tom Scott*\n**[Exponentiation by Squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring)**  | :star: | *Wikipedia*\n\n\n---\n## 0x06 ~ Computer Vision \u0026 AI\n\n\u003e **It is through science that we prove, but through intuition that we discover** ― *[Henri Poincaré](https://en.wikipedia.org/wiki/Henri_Poincar%C3%A9)*\n\nTitle | How Interesting | Author\n---|---|---\n**[OpenCV Tutorial](https://docs.opencv.org/2.4/opencv_tutorials.pdf)** | :star::star::star:\n\n\n---\n## 0x07 ~ C++ Optimization\n\n\u003e **C++ is a horrible language. It's made more horrible by the fact that a lot of substandard programmers use it, to the point where it's much much easier to generate total and utter crap with it** ― *Linus Torvalds 2007*\n\nTitle | How Interesting | Author\n---|---|---\n**[Optimizing software in C++](https://www.agner.org/optimize/optimizing_cpp.pdf)** | :two_hearts: | *by Agner Fog*\n**[Intel Intrinsics Guide](https://software.intel.com/sites/landingpage/IntrinsicsGuide/)** *[What is it](https://en.wikipedia.org/wiki/Intrinsic_function)* | :two_hearts: | *Intel*\n**[Software Performance and Indexing](https://lemire.me/en/#publications)** | :two_hearts: | *by [Daniel Lemire](https://github.com/lemire)*\n**[\"Low Latency C++ for Fun and Profit\"](https://www.youtube.com/watch?v=BxfT9fiUsZ4)** | :star::star::star::star: | *by Carl Cook*\n**[Why I Created C++](https://www.youtube.com/watch?v=JBjjnqG0BP8)** | :star::star::star: | *Bjarne Stroustrup*\n**[CppCon 2018 “High-Radix Concurrent C++”](https://www.youtube.com/watch?v=75LcDvlEIYw)** | :star::star::star: | *Olivier Giroux*\n**[C++ Features](https://github.com/AnthonyCalandra/modern-cpp-features)**| :star::star::star: | *by Anthony Calandra*\n\n\n---\n## 0x08 ~ Assembly Optimization\n\n\u003e **People say that you should not micro-optimize. But if what you love is micro-optimization... that's what you should do** ― *Linus Torvalds*\n\nTitle | How Interesting | Author\n---|---|---\n**[Intel® 64 and IA-32 architectures software developer’s manual](https://software.intel.com/en-us/download/intel-64-and-ia-32-architectures-sdm-combined-volumes-1-2a-2b-2c-2d-3a-3b-3c-3d-and-4)** | :two_hearts: | *Intel*\n**[Optimizing subroutines in assembly x86 language](https://www.agner.org/optimize/optimizing_assembly.pdf)** | :two_hearts: | *by Agner Fog*\n**[Online Compiler Explorer](https://godbolt.org/)** | :star::star::star::star::star: | *by Godbolt*\n**[Online Assembler and Disassembler](https://defuse.ca/online-x86-assembler.htm#disassembly)** | :star::star::star::star: | *by [Taylor Hornby](https://github.com/defuse)*\n**[A Guide to inline assembly for C and C++](https://www.ibm.com/developerworks/rational/library/inline-assembly-c-cpp-guide/)** | :star::star::star::star: | *by Salma Elshatanoufy and William O'Farrell*\n**[Tips for Golfing in x86/x64 Bytecode](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code)** | :star::star::star: | *by StackExchange*\n**[The Art of Assembly Language](http://www.staroceans.org/kernel-and-driver/The.Art.of.Assembly.Language.2nd.Edition.pdf)** | :star::star: | *by Randal Hyde*\n**[GDB Tutorial](https://www.cs.cmu.edu/~gilpin/tutorial/)** | :star::star: | *by Andrew Gilpin*\n**[Examining Arm VS x86 Memory Models with Rust](https://www.nickwilcox.com/blog/arm_vs_x86_memory_model/)** | :two_hearts: | *by [Nick Wilcox](https://www.nickwilcox.com/blog/)*\n\n---\n## 0x09 ~ Functional Programing *[by Leonard Marquez](https://github.com/keuhdall)*\n\n\u003e **A monad is just a monoid in the category of endofunctors, what's the problem?** ― *James Iry*\n\nTitle | How Interesting | Author\n---|---|---\n**[Learn You a Haskell for Great Good!](http://learnyouahaskell.com/chapters)** | :two_hearts: | *by Miran Lipovača*\n**[Functors, Applicatives, And Monads In Pictures](http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html)** | :two_hearts: | *by Aditya Bhargava*\n**[Category Theory course by Bartosz Milewski](https://www.youtube.com/watch?v=I8LbkfSSR58\u0026list=PLbgaMIhjbmEnaH_LTkxLI7FMa2HsnawM_)** | :star::star::star::star::star: | *by Bartosz Milewski*\n**[Wise Man's Haskell](https://andre.tips/wmh/)** | :star::star::star::star: | *by Andre Popovitch*\n**[Real World Haskell](http://book.realworldhaskell.org/read/)** | :star::star::star: | *by Bryan O'Sullivan*\n**[Martin Odersky's Scala course](https://www.coursera.org/learn/progfun1)** | :star::star: | *by Martin Odersky*\n\n\n---\n## 0x0A ~ Computer Architecture\n\n\u003e **And luckily right at that moment my wife went on a 3 weeks vacation to take my one year old (roughly) to visit my in-laws who were in California, this period long, 1 week, 1 week, 1 week... and we had Unix** ― *[Ken Thompson](https://en.wikipedia.org/wiki/Ken_Thompson), [VCF East 2019](https://www.youtube.com/watch?v=EY6q5dv_B-o\u0026t=23m11s)*\n\nTitle | How Interesting | Author\n---|---|---\n**[Digital Design and Computer Architecture](http://www.csit-sun.pub.ro/courses/cn2/Digital_design_book/Digital%20Design%20and%20Computer%20Architecture.pdf)** | :star::star::star::star: | **  \n**[X86 vs ARM](https://fossbytes.com/cpu-comparison-x86-arm-cpu-benchmark/amp/)** | :star::star::star: | *Fossbytes*  \n**[MIPS Processors](https://stackoverflow.com/questions/2635086/mips-processors-are-they-still-in-use-which-other-architecture-should-i-learn)** | :star::star: | *Stack Overflow*  \n\n\n---\n## 0x0B ~ Misc\n\n\u003e **...and Unix is an example of a proper name, and, is not likely to be in the dictionary ever** ― *[Brian W. Kernighan](https://en.wikipedia.org/wiki/Brian_Kernighan) (1982)*\n\nTitle | How Interesting | Author\n---|---|---\n**[AVIF for Next Generation Image Coding](https://netflixtechblog.com/avif-for-next-generation-image-coding-b1d75675fe4)** | :star::star::star::star::star: | *By Aditya Mavlankar, Jan De Cock, Cyril Concolato, Kyle Swanson, Anush Moorthy and Anne Aaron*\n**[UNIX AT\u0026T Archives film from 1982](https://www.youtube.com/watch?v=XvDZLjaCJuw)** | :two_hearts: | *by Bell Laboratories*\n**[A Super Mario 64 decompilation](https://github.com/agavrel/sm64)** | :star::star::star::star::star: | *by a bunch of clever folks*\n**[The Go Programming Language](https://www.gopl.io/ch1.pdf)** | :star::star::star::star::star: |  *by Alan A. A. Donovan and Brian W. Kernighan*\n**[Vim 101 Quick Movement](https://medium.com/usevim/vim-101-quick-movement-c12889e759e0)** | :star::star::star::star: | *Alex R. Young*\n**[Software Version Control Visualization](https://github.com/acaudwell/Gource)** : :star::star::star::star: | *by [Andrew Caudwell](https://github.com/acaudwell)*\n**[Math for Game Programmers: Dark Secrets of the RNG](https://www.youtube.com/watch?v=J5qnnxFoBss)** | :star::star::star: | *by Shay Pierce*\n**[Clean Code](https://www.investigatii.md/uploads/resurse/Clean_Code.pdf)** | :star::star::star: | *by Robert C. Martin*\n**[Why Java Suck](https://tech.jonathangardner.net/wiki/Why_Java_Sucks)** | :star: | *by Jonathan Gardner*\n**[XOR Linked List – A Memory Efficient Doubly Linked List](http://en.wikipedia.org/wiki/XOR_linked_list)** | :star: | *Wikipedia* \n**[XOR Linked List – C Implementation](https://stackoverflow.com/questions/3531972/c-code-for-xor-linked-list)** | :star: | *StackOverFlow*\n\n\n---\n## 0x0C ~ Mobile App Development\n\nTitle | How Interesting | Author\n---|---|---\n**[Framework: Flutter Hello World](https://flutter.dev/docs/get-started/codelab)** | :two_hearts: | *by Flutter Team (Google)*\n**[Images: About Webp](https://www.smashingmagazine.com/2019/10/speed-up-your-website-webp)** | :star::star: | *Suzanne Scacca*\n\n---\n## 0x0D ~ Science-Fiction Masterpieces\n\n\u003e **To succeed, planning alone is insufficient. One must improvise as well** ― *Isaac Asimov, Foundation*\n\nFormat | Title | How Interesting | Author\n---|---|---|---\nBook | **[The Foundation](https://en.wikipedia.org/wiki/Foundation_series)** | :two_hearts: | *by [Isaac Asimov](https://en.m.wikipedia.org/wiki/Isaac_Asimov)*\nBook | **[The Hitchhiker's Guide to the Galaxy](https://www.goodreads.com/book/show/841628.The_Hitchhiker_s_Guide_to_the_Galaxy)** | :two_hearts: | *by [Douglas Adams](https://en.m.wikipedia.org/wiki/Douglas_Adams)*\nAudioBook | **[The Hitchhiker's Guide to the Galaxy](https://www.youtube.com/watch?v=dPbr0v_V-cI\u0026list=PLYT7LhCzuTTdtIGcDOP-PPMxAWYo3qF5r\u0026index=3\u0026t=3167s)** | :two_hearts: | *by Douglas Adams and read by Stephen Moore*\nMovie | **[Ready Player One](https://en.wikipedia.org/wiki/Ready_Player_One_(film))** | :two_hearts: | by *[Steven Spielberg](https://en.wikipedia.org/wiki/Steven_Spielberg)*\nMovie | **[Matrix](https://en.wikipedia.org/wiki/The_Matrix)** | :two_hearts: | *by the Wachowskis*\nBook | **[Hyperion](https://en.m.wikipedia.org/wiki/Hyperion_(Simmons_novel))** | :star::star::star::star: | *by [Dan Simmons](https://en.m.wikipedia.org/wiki/Dan_Simmons)*\nMovie | **[War Games](https://en.wikipedia.org/wiki/WarGames)** | :star::star::star: | *directed by John Badham*\nBook | **[Elon Musk Biography](https://www.goodreads.com/book/show/25541028-elon-musk)** | :star::star::star::star::star: | *by Ashlee Vance*\n\n\n---\n# Tutorials\n\n\u003ca href=\"https://www.youtube.com/watch?v=Jen46qkZVNI\u0026t=30s\" target=\"_blank\"\u003e\u003cimg src=\"http://img.youtube.com/vi/Jen46qkZVNI/0.jpg\"\nalt=\"Boxer's Perfect Rush SCV\" width=\"240\" height=\"180\" border=\"10\" /\u003e\u003c/a\u003e\n\n---\n## 0x00 ~ Optimization - Aiming for the lowest latency\n\nWhen you want to aim for lowest latency - *i.e maximum speed* - there are many things that will improve your program to create a better binary: Optimization flag, parallelization, vectorization and carefully crafting your algorithm.\n\n\n### Optimization flags\n\nEspecially for Computer Graphics projects, you will want to turn on these optimization flags, [listed on gcc website](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html).\n\n\u003e Without any optimization option, the compiler’s goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code.\nTurning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.\n\n**To use it simply compile the program with:**\n```\ngcc -O2 a.c\n```\nNB: It is the letter 'o' and not a zero. You may also use O3.\n\n\n### Multithreading and Parallelization\n\nThe historical (and current) approach is to add more power via [multithreading](https://en.wikipedia.org/wiki/Multithreading_(computer_architecture)), [multiprocessing](https://en.wikipedia.org/wiki/Multiprocessing), [Grid Computing](https://en.wikipedia.org/wiki/Grid_computing) or even [Cloud Computing](https://en.wikipedia.org/wiki/Cloud_computing). Two libraries exist for this use: [OpenMP](https://www.openmp.org/wp-content/uploads/openmp-examples-4.5.0.pdf) and [pthread](http://man7.org/linux/man-pages/man7/pthreads.7.html), you will have to compile respectively with:\n```\ngcc -fopenmp -O3 a.c\n```\nand:\n```\ngcc -pthread -O3 a.c\n```\n\n\n### [Vectorization](https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions)\n\n\u003e Modern graphics processing units (GPUs) are often wide SIMD implementations, capable of branches, loads, and stores on 128 or 256 bits at a time.\nIntel's latest AVX-512 SIMD instructions now process 512 bits of data at once.\n\nAs a double is 64 bits - *i.e 8 bytes or octets* - **instead of iterating overs value 1 by 1, you will be able to compute up to 8 double at the time** - *i.e 512 / 64* - if your computer support it (but most likely, as of 2020, your computer will only handle 256 bits register).\n\n**Vectorization the most efficient way to quickly gain performance gains without the overhead of threads' initialization**.\n\n**Demonstration: Getting Min and Max value from a float array**\n```c\n/* Vectorization example by agavrel */\n#include \u003cstdio.h\u003e  // printf\n#include \u003cstdlib.h\u003e // rand()\n#include \u003ctime.h\u003e   // time\n#include \u003cxmmintrin.h\u003e  // 128 bits register _m128\n\nfloat m128_max_float(__m128 src) {\n    __m128 n[4];\n\n\t// a) n[0] = src \u003e\u003e 64                                  So lets say src is composed of floats a b c d, it becomes 0 0 a b\n    n[0] = _mm_shuffle_ps(src, src, _MM_SHUFFLE(0,0,3,2));\n\t// b) n[1] = {max(a,0), max(b,0) max(a,c) max(b,d)}     NB: actually we don't care about the two highest float at this point, I will call them 'x': {x, x max(a,c) max(b,d)}\n    n[1] = _mm_max_ps(src, n[0]);                             \n\t// c) n[2] = n[1] \u003e\u003e 32                                 So n2 become {0 x x max(a,c)}\n    n[2] = _mm_shuffle_ps(n[1], n[1], _MM_SHUFFLE(0,0,0,1));\n\t// d) n[3] = {x x x max(max(a,c), max(b,d))}\n    n[3] = _mm_max_ps(n[1], n[2]);                            \n\n    return _mm_cvtss_f32(n[3]);   // d) Hence max(a,b,c,d), stored in the lowest 32 bits of n[3], is loaded into a float that we return. We don't care about the other bits\n}\n\nfloat m128_min_float(__m128 src) {\n    __m128 n[4];\n\n    n[0] = _mm_shuffle_ps(src, src, _MM_SHUFFLE(0,0,3,2));\n    n[1] = _mm_min_ps(src, n[0]);\n    n[2] = _mm_shuffle_ps(n[1], n[1], _MM_SHUFFLE(0,0,0,1));\n    n[3] = _mm_min_ps(n[1], n[2]);\n\n    return _mm_cvtss_f32(n[3]);\n}\n\n#define SIZE  1000000000L // 1 billion. Yes.\n\nvoid  get_min_max(long i, float array[i]) {\n  __m128 max;\n  __m128 min;\n  \n  max = _mm_loadu_ps(array); // will load first 4 float into max\n  min = _mm_loadu_ps(array); // will load first 4 float into min\n  while ((i -= 4L))\n  {\n    __m128 tmp = _mm_loadu_ps(array + i);\n    max = _mm_max_ps(max, tmp);\n    min = _mm_min_ps(min, tmp);\n  }\n\n  printf(\"Max value: %f\\t Min value: %f\\n\", m128_max_float(max), m128_min_float(min));\n}\n\nvoid  get_min_max_like_bocalian(long size, float array[size]) {\n  float max;\n  float min;\n  int i;\n\n  max = array[0];\n  min = array[0];\n  i = 1L;\n  while (i \u003c size)\n  {\n    float tmp = array[i++];\n    max = tmp \u003c max ? max : tmp;\n    min = tmp \u003e min ? min : tmp;\n  }\n\n  printf(\"Max value: %f\\t Min value: %f\\n\", max, min);\n}\n\nint main()\n{\n  long i;\n  float *data;\n  clock_t time;\n\n  srand(time(NULL));  // seed\n  data = (float *)malloc(SIZE * sizeof(float));\n  i = -1L;\n  while (++i \u003c SIZE) {\n    data[i] = (float)rand() / (float)(RAND_MAX) * 1000.0f;\n   /* printf(\"%.02f\\t\\t\", data[i]);     // I commented these lines because it slows considerably the program.\n    if (!(i \u0026 15))\n      printf(\"\\n\");*/\n  }\n\n  time = clock();\n  get_min_max(SIZE, data);\n  time = clock() - time;\n  double elapsed_time = ((double)time) / CLOCKS_PER_SEC;\n  printf(\"Executed in %f seconds\\n\", elapsed_time);\n\n  time = clock();\n  get_min_max_like_bocalian(SIZE, data);\n  time = clock() - time;\n  elapsed_time = ((double)time) / CLOCKS_PER_SEC;\n  printf(\"Executed in %f seconds\\n\", elapsed_time); \n\n  return 0;\n}\n```\n\nAnd compile with:\n```\ngcc vectorization.c -O3  \u0026\u0026 ./a.out \n```\n\nYou will notice that the vectorized approach will be about 3 times faster (NB: For this specific example). If I was using mm256 or mm512 registers, the vectorized program would be even faster by a factor of 2 and 4 respectively.\n\n*Now that you realize the performance boost, how about using what you just learn for your RayTracing project?*\n\n\n### Combining Optimization Flags, Parallelization and Vectorization\n\n*a) **You can take a look at [this very interesting project](https://github.com/expr-fi/fastlwc/blob/master/fastlwc-mt.c)** which aim to show how fast wc can get using the various tools C has to offer to optimize speed. After downloading the file, you will also need to download the header: [simd.h](https://github.com/expr-fi/fastlwc/blob/master/simd.h), which make use of [Intel intrinsic](https://software.intel.com/sites/landingpage/IntrinsicsGuide/).*  \n\n*b) Compile it with the flags:*\n```\ngcc fastlwc-mt.c -fopenmp -O3\n```\n\n*c) Create a random file:*\n```\ndd if=/dev/urandom of=sample.txt bs=64M count=16 iflag=fullblock\n```\n\n*d) Compare wc with the new binary with:*\n```\ntime ./a.out sample.txt \\\n\u0026\u0026 time wc sample.txt\n```\n\n### The Right Algorithm\n\n**The right algorithm is usually the corner stone of an efficient program.**\n\n*How about solving this [algorithm problem](https://github.com/agavrel/Nailing-the-Coding-Interview/tree/master/math/the_dancer):*\n\n```c\nint32_t dancer_position(uint32_t time_elapsed) { ;}\n```\n\n\n### Exploring Compiler's Assembly Output\n\nLet's take and example with the brilliant [UTF-8](https://en.wikipedia.org/wiki/UTF-8) implementation, especially at how continuation bytes are designed: \n\n\u003e continuation bytes start with 10 while single bytes start with 0 and longer lead bytes start with 11\n\nLet's say that you have to write a function that determines if the byte is a continuation one, you can think of many ways that would end with the same result. But they will have a different output in their assembly.\n\n\nYou can retain the two first bits wwith ```\u0026 0b11000000``` and then make sure that the first one is set and the second one is not with ```== 0b10000000``` :\n```c\n#include \u003cstdbool.h\u003e\n\nbool is_utf8_continuation_byte(char c) {\n\treturn ((c \u0026 0b11000000) == 0b10000000);  \n}\n```\n\nWhich corresponds to the following compiler output with ```gcc x86-64 9.3 with -O3 optimization flag``` :\n```asm\nand     edi, 192\ncmp     edi, 128\nsete    al\n```\n\n\nAnother way would be to shift the bits to the right:\n```c\nbool is_utf8_continuation_byte(char c) {\n\treturn (!((((unsigned char)c \u003e\u003e 6) ^ 0b10)));\n}\n```\nHere I cast c into unsigned in order to be able to shift the MSB to the right with ```(unsigned char)c```  \nThen I shift it 6 times to the right with ``` \u003e\u003e 6``` because we do not care about the content of the 6 lowest bits.  \nFinally I xor the result by 0b10 with ```^ 0b10```, which corresponds to specification of a continuation byte as quoted before.\nAs a number xored by itself gives 0, I use the exclamation mark ! to reverse the result from 0 to 1. (Else we would have to rename the function ```is_not_utf8_continuation_byte```)\n\n\nIt is not producing the following output that you could imagine:\n```asm\nsar     edi, 6\nxor     edi, 2\nnot\t\tedi,\n```\n\nBut the optimized version:\n```asm\nmovzx   edi, dil\nsar     edi, 6\ncmp     edi, 2\nsete    al\n```\nIt's even less efficient.\n\n\nFinally since the valid range 0b10111111 to 0b10000000 (corresponding to -128 to -65, both included), you can add 0b01000000 and check if the byte is negative:\n```c\nbool is_utf8_continuation_byte(char c) {\n\treturn (c + 0b01000000 \u003c 0);\n}\n```\n\nIn other word you compare to -64 and check if it is lower:\n```asm\ncmp     dil, -64\nsetl    al\n```\n\n**To see the assembly output you can use the following command which will generate an assembly file with intel syntax (more readable than AT\u0026T):**\n```\ngcc -O3 -S -masm=intel a.c \u0026\u0026 cat a.s\n```\n\n*or use the excellent [compiler explorer from godbolt](https://godbolt.org/)*\n\n**I hope that you liked this demonstration that shows that functions with same behaviors can produce different assembly output, hence being more or less efficient. If you want to build your program to be the most efficient you should explore the assembly code of functions in critical loops**\n\n\n---\n## 0x01 ~ Computer Graphics - Using [SDL2](https://www.libsdl.org/index.php) to create Fractal\n\n### Using SDL2 to create Computer Graphics\nYou can follow tutorials to create a simple program with SDL on [Lazyfoo's website](https://lazyfoo.net/tutorials/SDL/01_hello_SDL/linux/index.php) or on SDL2 official website.\n\nYou will also have to install SDL2:\n```\nbrew install sdl2\n```\n\nWith SDL2 you have to first ```init_sdl``` - *see function below*. Then you will keep the user entertained with a loop ```while (42)``` that can only be escaped by clicking on the the close button or pressing escape. While the loop is active, user's actions will be recorded thanks to ```SDL_PollEvent```. You then draw pixel by using ```SDL_RenderDrawPoint``` and you refresh image with ```SDL_RenderPresent```.\n\n### Example with a Barnsley Fern Fractal\n\n[Michael Barnsley](https://en.wikipedia.org/wiki/Michael_Barnsley) was a British mathematician who coined a fractal algorithm to represent a fern.  \n\n![Barnsley Fern](https://raw.githubusercontent.com/agavrel/42_CheatSheet/master/img/BarnsleyFern.png)\n\nThe algorithm is explained in detail on [wikipedia](https://en.wikipedia.org/wiki/Barnsley_fern)  \n\nFind below the code for the whole program, compile it with :\n```\ngcc barnsley.c -lSDL2 -O3\n```\n\nYou will need about 10 000 iterations of n to draw the shape. On each keypress you will increase the number of iterations by 400.\n```c\n#pragma message \"\\033[1;31mRequire SDL2\\033[0m, \\033[1;92mbrew install sdl2\\033[0m and compile with \\033[1;5;36mgcc barnsley.c -lSDL2\\033[0m  \u0026\u0026 ./a.out  \" __FILE__ \"...\"\n// gcc main.c -lSDL2 -O3 -Wall -Werror -Wextra --pedantic\u0026\u0026 ./a.out\n#include \u003cstdio.h\u003e\n#include \u003cSDL2/SDL.h\u003e\n#include \u003cstdbool.h\u003e\n\n#define WINDOW_WIDTH\t600\n#define\tWINDOW_HEIGHT\t800\n\ntypedef struct\t\ts_cnb\n{\n\tdouble\t\t\treal;\n\tdouble\t\t\timag;\n}\t\t\t\t\tt_cnb;\n\ntypedef struct\t\ts_pixel\n{\n\tint\t\t\t\tx;\n\tint\t\t\t\ty;\n}\t\t\t\t\tt_pixel;\n\nvoid\tbarnsley(SDL_Renderer *renderer, t_cnb *c) {\n\tfloat\trng;\n\tt_pixel\ti;\n\tstatic const float probability[3] = {0.01f, 0.08f, 0.15f};\n\tlong n = 400;\n\n\twhile (n--) {\n\t\trng = ((float)rand() / (float)RAND_MAX);\n\t\tif (rng \u003c= probability[0]) {\n\t\t\tc-\u003ereal = 0;\n\t\t\tc-\u003eimag *= 0.16f;\n\t\t}\n\t\telse if (rng \u003c= probability[1]){\n\t\t\tc-\u003ereal = -0.15f * c-\u003ereal + 0.28f * c-\u003eimag;\n\t\t\tc-\u003eimag = 0.26f * c-\u003ereal + 0.24f * c-\u003eimag + 0.44f;\n\t\t}\n\t\telse if (rng \u003c= probability[2]) {\n\t\t\tc-\u003ereal = 0.2f * c-\u003ereal + -0.26f * c-\u003eimag;\n\t\t\tc-\u003eimag = 0.23f * c-\u003ereal + 0.22f * c-\u003eimag + 1.6f;\n\t\t}\n\t\telse {\n\t\t\tc-\u003ereal = 0.85f * c-\u003ereal + 0.04f * c-\u003eimag;\n\t\t\tc-\u003eimag = -0.04f * c-\u003ereal + 0.85f * c-\u003eimag + 1.6f;\n\t\t}\n\t\ti.x = (c-\u003ereal + 3) * 70;\n\t\ti.y = WINDOW_HEIGHT - c-\u003eimag * 70;\n    \tSDL_RenderDrawPoint(renderer, i.x, i.y);\n\t}\n}\n\nbool\terror_sdl(char *error_msg) {\n\tprintf( \"%s! SDL_Error: %s\\n\", error_msg, SDL_GetError() );\n\treturn false;\n}\n\nbool\tinit_sdl(SDL_Window **window, SDL_Renderer **renderer) {\n\tif (SDL_Init(SDL_INIT_VIDEO) \u003c 0)\n\t\treturn (error_sdl(\"SDL could not initialize!\"));\n\tSDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_HEIGHT, 0, window, renderer);\n\tif (*window == NULL)\n\t\treturn (error_sdl(\"Window could not be created!\"));\n\tSDL_SetRenderDrawColor(*renderer, 0, 0, 0, 0);\n\tSDL_RenderClear(*renderer);\n    SDL_SetRenderDrawColor(*renderer, 0xbf, 0xff, 0, 0);\n\n\treturn true;\n}\n\nint\t\tmain(void) {\n    SDL_Event event;\n    SDL_Window *window;\n\tSDL_Renderer *renderer;\n\tt_cnb c;\n\t\n\tif (!(init_sdl(\u0026window, \u0026renderer)))\n\t\treturn 1;\n\n\tc = (t_cnb) {.real = 0, .imag = 0}; // PS: legal for Norminette\n    while (42) {\n\t\tif (SDL_PollEvent(\u0026event)) {\n\t\t\tif (event.type == SDL_QUIT)\n\t\t\t\tbreak ;\n\t\t\telse if (event.type == SDL_KEYDOWN) {\n\t\t\t\tif (event.key.keysym.sym == SDLK_ESCAPE)\n\t\t\t\t\tbreak ;\n\t\t\t\tbarnsley(renderer, \u0026c);\n\t\t\t\tSDL_RenderPresent(renderer);\n\t\t\t}\n\t\t}\n    }\n    SDL_DestroyRenderer(renderer);\n    SDL_DestroyWindow(window);\n    SDL_Quit();\n    return EXIT_SUCCESS;\n}\n```\n\n---\n## 0x02 ~ Hacking - Buffer Overflow\n\n### Introduction\n\nLet's take a look at the function strcpy, shall we? Type ```man strcpy``` in your terminal:\n\n\u003e *The  strcpy() function copies the string pointed to by src, including the terminating null byte ('\\0'), to the buffer pointed to by dest.  The strings may not overlap, and the destination string dest must be large enough to receive the copy.  Beware of buffer overruns!  **(See BUGS.)***\n\n**NB: Usage of brackets for what is considered as one of the most critical security flaw in the world**\n\n\u003e ***BUGS:**  \nIf  the  destination  string of a strcpy() is not large enough, then anything might happen ― **NB: Undefined Behavior**.  Overflowing fixed-length string buffers is a favorite cracker technique for taking complete control of the machine.  Any time a program reads or copies data into a buffer, the program first needs to  check  that  there's  enough  space. This may be unnecessary if you can show that overflow is impossible, but be careful: programs can get changed over time, in ways that may make the impossible possible.*\n\n```c\n#include \u003cstring.h\u003e\n#include \u003cstdio.h\u003e\n\nint main(void) {\n\tchar s[11];\n\n\tstrcpy(s, \"hello world\");\n\tputs(s);\t\n\n\treturn 0;\n}\n```\n\nWhile this look okay if you count each letter, if you happen t","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagavrel%2F42_cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fagavrel%2F42_cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fagavrel%2F42_cheatsheet/lists"}