Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 135 ยท Advanced C

Best Practices and Common Mistakes

Write safer, cleaner C - strict warnings, safe input, checking every return value, clear memory ownership, const correctness, and the beginner bugs everyone makes.

C trusts the programmer completely. It won't stop you from writing past an array, forgetting to free memory, or ignoring an error. That freedom is why C is fast and runs everywhere, but it also means the safety has to come from you: from the habits you build and the conventions you follow every time, not just when you remember. Experienced C programmers aren't people who never make mistakes; they're people whose habits make mistakes rare and easy to catch.

This lesson collects those habits in one place. You've met most of them already, spread across the course. Here they're organized as a checklist you can apply to every program: let the compiler help you, read input safely, check every result, make memory ownership obvious, use const, and recognize the classic beginner bugs on sight. It pairs well with Undefined Behavior and Debugging C Programs.

1. Let the compiler do the first review

Warnings are free bug reports. Turn on many of them and don't allow any to survive. A good flag set for your own projects:

Terminal
gcc -std=c17 -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wformat=2 \
    -Wstrict-prototypes -Wmissing-prototypes -Werror -g main.c -o app
  • -Wall -Wextra enable the essential warnings (our editor uses these two).
  • -Wpedantic warns about non-standard extensions.
  • -Wshadow catches a local variable hiding another with the same name.
  • -Wconversion flags implicit conversions that can lose data, like double to int or long to int. It's noisy at first, but every warning is a question worth answering.
  • -Wformat=2 checks printf/scanf format strings more strictly.
  • -Werror turns warnings into errors, so they can't scroll past unnoticed.

In development builds, also add -fsanitize=address,undefined so memory errors and undefined behavior stop the program at the faulty line. A static analyzer (gcc -fanalyzer, clang --analyze, clang-tidy or cppcheck) finds deeper problems such as leaks on error paths. Set these up once in your build tool and you get them on every build.

2. Read input defensively

User input is the most common source of crashes and security holes. Assume it can be empty, too long, the wrong type, or missing entirely.

  • Never use gets. It was removed in C11 because it can't limit how much it writes.
  • Read whole lines with fgets, then parse them with strtol, strtod or sscanf. This keeps bad input from getting stuck in the buffer.
  • Check that the whole line was consumed and that the value is in range.
  • Handle end of input. fgets returns NULL at EOF; scanf returns EOF. A loop that ignores this spins forever.

Here's a reusable function that reads an integer in a range, rejecting everything else. The Input box already holds some bad lines followed by good ones:

C A robust integer reader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The function survives every bad line: a word, a number with junk after it, an empty line and an out-of-range value. Then 42 is accepted for the age and 7 for the guests. Delete the last line of input and run again: the program reports "no guest count given" instead of looping forever. Converting Strings and Numbers explains strtol in depth.

3. Check every return value

Functions in C report failure through their return value, and the language never forces you to look at it. Make it a reflex: if a function can fail, check it.

Function Failure signal
malloc, calloc, realloc NULL
fopen NULL (and errno is set)
fgets NULL at end of file or on error
scanf, sscanf fewer items than requested, or EOF
strtol, strtod end == start (nothing parsed), errno == ERANGE
fclose, fflush EOF; for files you wrote, this can be the first sign of a full disk
fread, fwrite fewer items than requested
pthread_create, thrd_create a non-zero error code

realloc deserves special care. If it fails, it returns NULL but leaves the old block untouched. Writing p = realloc(p, n) loses your only pointer to that block, which is a leak and a crash waiting to happen. Always use a temporary:

C Growing a buffer with realloc safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The same program also shows two more habits: sizeof *values instead of sizeof(int) (it stays correct if the type ever changes), and returning EXIT_FAILURE from main so scripts can tell the program failed. Building a Dynamic Array develops this into a reusable type.

Tip: In C23 you can mark your own functions [[nodiscard]] so the compiler warns when a caller ignores the result. It's ideal for functions that return error codes. See Modern C.

4. Make ownership obvious

Every block of memory from malloc must be freed exactly once, by exactly one owner. Leaks, double frees and use-after-free all come from confusion about who that owner is. Follow a few conventions and the confusion disappears:

  • Pair every creator with a destroyer. If inventory_create allocates, inventory_destroy frees, and both live in the same module. Callers never free the internals themselves.
  • Document transfers. A comment such as "the caller must free the returned string" or "takes ownership of node" on the function prototype.
  • Make the destroyer accept NULL, like free does, so cleanup code can call it unconditionally.
  • Set pointers to NULL after freeing them when the variable stays in use, so a second free is harmless and a use crashes clearly instead of silently.
  • Use one cleanup path. When a function acquires several resources, a single cleanup section at the end, reached with goto, releases them in reverse order. This is the one widely accepted use of goto (see break, continue and goto).
C Create, destroy and a single cleanup path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

calloc for the struct is a small trick that makes the cleanup simple: because every pointer member starts as NULL, the fail section can free all of them no matter which step failed.

5. Use const to state intent

Mark everything that shouldn't change as const, especially pointer parameters. size_t count_vowels(const char *text) promises callers that their string won't be modified, lets them pass string literals, and makes the compiler reject accidental writes inside the function. sensor_average(const sensor *s) above does the same for a struct. The rules are in const and Pointers.

  • Pointer parameters that are only read: const T *.
  • Lookup tables and messages: static const arrays.
  • String literals: always const char *, because modifying a literal is undefined behavior.

6. Keep sizes, strings and integers honest

  • Pass the size with every buffer (char *buf, size_t size) and use size_t for sizes and indexes.
  • Leave room for '\0'. A string of length n needs n + 1 bytes.
  • Prefer bounded functions: snprintf over sprintf, fgets over gets, explicit length checks before strcpy/strcat. Remember that strncpy doesn't always add a terminator (Safe String Handling).
  • Don't mix signed and unsigned in comparisons. -1 < sizeof(int) is false, because -1 converts to a huge unsigned value (Type Conversions).
  • Check arithmetic on untrusted values before doing it, or use C23 ckd_add/ckd_mul (Type Limits).
  • Use fixed-width types (uint8_t, int32_t) when the exact size matters, such as in file formats and bit manipulation.

7. Structure code for humans

  • Small functions that do one thing, with names that say what that is: parse_header, print_report.
  • Minimize global variables. Pass data through parameters; if a global is truly needed, make it static so it's private to its file (Scope and Storage Classes).
  • Make file-local functions static, and put only the public interface in headers (Multi-File Programs).
  • Prefer enum, const and C23 constexpr over #define for constants, and static inline functions over function-like macros, unless you really need the preprocessor (Macros).
  • Declare variables where they're used, initialized, in the smallest possible scope.
  • Always use braces for if, else, for and while, even around one line, so adding a second line can't silently fall outside the block.
  • Use a formatter such as clang-format and a consistent naming style (this course uses snake_case and UPPER_CASE for macros).
  • Comment the why, not the what. i++; /* increment i */ helps no one; /* skip the header row */ does (Comments).

8. The classic beginner bugs

These mistakes appear in nearly every beginner's code, and many in professionals' code too. Learn to spot them on sight.

Bug What happens Fix
if (x = 5) Assigns 5, the condition is always true if (x == 5); -Wall warns
if (x > 0); The ; is an empty body; the block always runs Remove the semicolon
case without break Falls through into the next case Add break, or C23 [[fallthrough]]; when intended
for (i = 0; i <= n; i++) on an n-element array Reads/writes one past the end i < n
if (name == "admin") Compares addresses, not text strcmp(name, "admin") == 0
scanf("%d", n) Missing &: writes to a garbage address scanf("%d", &n), and check the return value
char c = getchar(); in an EOF loop EOF (-1) can't be told apart from a real byte int c = getchar();
average = sum / count; with ints Integer division truncates (double)sum / count
sizeof arr inside a function Gives the pointer size, not the array size Pass the length as a parameter
Returning the address of a local Dangling pointer after return Return by value, or allocate, or have the caller pass a buffer
int *p; *p = 3; Writes through an uninitialized pointer Point it at something first
Forgetting #include <string.h> Implicit declaration error (C99+) Include the header for every function you use

Here are several of these bugs in their corrected form, working correctly side by side:

C Classic bugs, fixed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program prints an average of 7.667 (not 7), confirms the strings match with strcmp, counts 10 letters in the Input box text, and prints exactly one level line. Try reintroducing a bug, such as average = sum / count without the casts or <= in the loop, and see what changes; in the <= case the result is undefined behavior, so the output may be anything.

A checklist before you call a program done

  1. It compiles with no warnings under -Wall -Wextra (better: the full set above with -Werror).
  2. It runs cleanly under -fsanitize=address,undefined and, where available, Valgrind.
  3. Every malloc, fopen and input call has its result checked.
  4. Every allocation has an owner that frees it, on every path, including errors.
  5. Input that's empty, too long, the wrong type or missing doesn't crash it.
  6. Pointer parameters that are only read are const.
  7. No magic numbers, no unexplained globals, no function longer than a screen without a good reason.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is wrong with p = realloc(p, new_size);?

    Assign the result to a temporary, check it for NULL, and only then overwrite the original pointer.
  2. 2. What does this print? int c = 0; if (c = 0) puts("zero"); else puts("not zero");

    c = 0 assigns 0 and the whole expression's value is 0, which is false, so the else branch runs. -Wall warns about an assignment used as a condition.
  3. 3. Why should a getchar loop store the result in an int instead of a char?

    With a char, either a real byte gets mistaken for EOF or EOF is never detected, depending on whether char is signed.
  4. 4. Which function signature best communicates that the function only reads the string?

    A pointer to const promises not to modify the characters, and lets callers pass string literals and other const data.
  5. 5. Inside void f(int arr[]), what does sizeof arr give?

    An array parameter is really a pointer, so sizeof gives the pointer size (8 on 64-bit systems). Pass the length separately.

Summary

  • Compile with strict warnings and -Werror; use sanitizers and static analyzers during development.
  • Read input with fgets and parse with strtol/strtod, checking for junk, range and end of input; never use gets.
  • Check every return value; grow memory with realloc through a temporary pointer.
  • Give every allocation one clear owner: create/destroy pairs, documented transfers, a single goto cleanup path, NULL after free.
  • Use const for data you only read, size_t for sizes, bounded string functions, and checked arithmetic on untrusted values.
  • Keep functions small, globals few and private, constants typed, braces everywhere.
  • Recognize the classic bugs: = vs ==, stray semicolons, missing break, <= loops, == on strings, missing &, char for getchar, integer division, sizeof on array parameters, dangling pointers.

Next: Project: Command Calculator