C-

C Security

C security practices for buffer overflow prevention, format string safety, and secure coding

Details

Language / Topic
cC
Category
Security

Rules

balanced
- Use `snprintf` instead of `sprintf` and `strncpy` instead of `strcpy` — always pass explicit buffer sizes to prevent overflows.
- Never pass user-supplied strings as the format argument to `printf`, `fprintf`, or `syslog` — use `printf("%s", user_input)` instead.
- Always validate array indices and pointer arithmetic against buffer bounds before dereferencing.
- Use `memset_s` or `explicit_bzero` to zero sensitive data (keys, passwords) before freeing — plain `memset` can be optimized away.
- Compile with `-fstack-protector-strong` and `-D_FORTIFY_SOURCE=2` to detect buffer overflows and format string attacks at runtime.
- Use `strnlen` to bound string operations on untrusted input — never assume external strings are null-terminated.
- Avoid `gets()` unconditionally — it was removed in C11. Use `fgets(buf, sizeof(buf), stdin)` with explicit size limits.
- Cast `malloc` return values explicitly and always check for `NULL` — use a wrapper macro that aborts on allocation failure in critical paths.
- Prefer `calloc(count, size)` over `malloc(count * size)` to prevent integer overflow in size calculations.