C Best Practices
Writing good C code goes beyond making it compile — it means writing code that's safe, readable, and maintainable. This includes checking return values, managing memory carefully, and following consistent style.
Because C gives you low-level control without many of the safety nets found in modern languages, disciplined habits are essential to avoid crashes, security vulnerabilities, and hard-to-find bugs.
// Good habits, not new syntaxMemory and safety habits
Always check malloc's return value for NULL, free every allocation exactly once, set freed pointers to NULL, and check array bounds carefully. Prefer safer functions (like fgets over gets) to avoid buffer overflows.
Readability and structure
Use meaningful variable and function names, keep functions short and focused, use constants instead of magic numbers, and comment on why code does something, not just what it does.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = malloc(sizeof(int));
if (p == NULL) {
fprintf(stderr, "Allocation failed\n");
return 1;
}
*p = 5;
printf("%d\n", *p);
free(p);
p = NULL;
return 0;
}5This example checks for allocation failure, frees memory, and nulls the pointer afterward.
#include <stdio.h>
#define MAX_USERS 100
int main() {
printf("Max users: %d\n", MAX_USERS);
return 0;
}Max users: 100Using a named constant instead of a magic number makes intent clear and updates easy.
Key points
- Always check the return value of malloc() and file operations for errors.
- Free every allocation exactly once, and avoid using pointers after freeing them.
- Use named constants instead of magic numbers for clarity.
- Compile with warnings enabled and fix them rather than ignoring them.
