diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 5ac5e55..c586a45 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -1,3 +1,4 @@ # Summary - [Formatting](./formatting.md) +- [Conventions](./conventions.md) \ No newline at end of file diff --git a/src/conventions.md b/src/conventions.md new file mode 100644 index 0000000..1aba074 --- /dev/null +++ b/src/conventions.md @@ -0,0 +1,14 @@ +# Conventions + +General conventions that C code should obey. + +## Memory allocation + +Always check the return value of `malloc`. If it is a null pointer, derefence it to immediately abort the processas as we cannot reasonable recover from OOM in most cases. If such a recovery is possible, recover instead. On some platforms, dereferencing a null pointer does _not_ abort the process. In these cases, the null pointer is a perfectly fine pointer, and just continue using it instead. Note that this derefence should usually be a volatile operation as the compiler would optimize it away otherwise. I have reported upstream issues on compilers about this, but they have not yet answered. + +If the pointer is non-null, `free` it directly after the `malloc` call. This prevents memory leaks of all sorts. Afterwards, +you can use it freely in your program. + +## Includes + +`#include` directives shall be placed at the start of the file. But usually, it's better to not use the preprocessor at all. Paste the code in by hand so that it is clearly visible in version control. \ No newline at end of file diff --git a/src/formatting.md b/src/formatting.md index 002bfbf..763734b 100644 --- a/src/formatting.md +++ b/src/formatting.md @@ -1 +1,36 @@ -# Formatting \ No newline at end of file +# Formatting + +The Nilstrieb C Style Guide Edition 2 mostly follows the principle of maximal readability. +Code, especially C code, is mostly read (by security researchers to find the vulnerabilities), +and therefore readability comes before writability. + +## Control flow + +Never use braces with `if`/`while`/`do`/`for` statements as they introduce clutter. If your +body cannot fit into a single line, make a new function instead. + +```c + #include + + void foo_if_body() { + printf("Hello, "); + printf("World!"); + } + + void foo() { + if (true) + foo_if_body(); + else + printf("True was false!"); + } +``` + +## Identation + +C code must be indented with 3 spaces. The toplevel should be indented as well. + +```c + #include + + int main() {} +``` \ No newline at end of file