Common Beginner Mistakes in C
Avoid the pitfalls every C beginner faces! Learn about the most common mistakes: = vs ==, integer division, array bounds, uninitialized variables, string issues, and pointer problems.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Avoid using = instead of == in conditions
- ✓Prevent integer division bugs
- ✓Handle array bounds correctly
- ✓Initialize variables properly
- ✓Work with strings safely
- ✓Use pointers without crashing
?Why Learn About Common Mistakes?
C is a powerful but unforgiving language. Unlike Python or JavaScript, C won't catch your mistakes at runtime — it just does something unexpected.
Save Hours
Recognize bugs instantly
Prevention
Avoid mistakes before they happen
Level Up
Write more professional code
Learning from mistakes is part of programming. Even experienced programmers encounter these issues — the key is recognizing them quickly!
01Common C Programming Mistakes
This guide covers the most common errors beginners encounter and how to avoid them. Each mistake includes wrong vs. correct examples.
Categories of Common Mistakes
Operator Errors
= vs ==, / issues
Array Errors
Bounds, size issues
String Errors
\0, buffer overflow
Pointer Errors
NULL, dangling, &
Initialization
Garbage values
Memory Errors
Leaks, double free
Danger Level
Compile Error
Caught early ✓
Wrong Output
Visible issue
Silent Bug
Works sometimes!
The worst bugs are the ones that "work" — they pass tests but fail in production!
02Using = Instead of ==
The most common C mistake! Using single = (assignment) when you meant double == (comparison).
Wrong
if (x = 5) { // ALWAYS true!
printf("Equal");
}
This ASSIGNS 5 to x, then checks if x (5) is truthy
Correct
if (x == 5) { // Compares x to 5
printf("Equal");
}
This COMPARES x with 5
Pro Tip: Yoda Conditions
Write if (5 == x) instead. If you accidentally use =, the compiler will error because you can't assign to a constant!
03Missing or Extra Semicolons
Missing Semicolon
int x = 10 // Missing ; here!
int y = 20;
Error message points to NEXT line, confusing!
Extra Semicolon After if
if (x > 5); // Empty statement!
{
printf("Always runs!");
}
The block runs regardless of condition!
Extra Semicolon in Loop
for (int i = 0; i < 10; i++); // Loop body is empty!
{
printf("%d", i); // Runs once, i=10
}
04Integer Division Surprise
When you divide two integers, C performs integer division — the decimal part is thrown away!
1#include <stdio.h>23int main() {4 // WRONG: Integer division5 float result1 = 5 / 2; // = 2.0, NOT 2.5!6 float result2 = 1 / 3; // = 0.0, NOT 0.333!7 8 printf("5 / 2 = %.2f (wrong!)\n", result1);9 printf("1 / 3 = %.2f (wrong!)\n", result2);10 11 // CORRECT: Cast to float BEFORE dividing12 float result3 = (float)5 / 2; // = 2.513 float result4 = 5.0 / 2; // = 2.514 float result5 = 1.0 / 3; // = 0.333...15 16 printf("(float)5 / 2 = %.2f (correct!)\n", result3);17 printf("5.0 / 2 = %.2f (correct!)\n", result4);18 printf("1.0 / 3 = %.2f (correct!)\n", result5);19 20 // Common mistake: calculating average21 int sum = 17, count = 5;22 23 float avg_wrong = sum / count; // = 3.0 (wrong!)24 float avg_right = (float)sum / count; // = 3.4 (correct!)25 26 printf("Average (wrong): %.2f\n", avg_wrong);27 printf("Average (right): %.2f\n", avg_right);28 29 return 0;30}05Array Out of Bounds
C doesn't check array boundaries! Accessing memory outside your array causes undefined behavior — crashes, wrong values, or security vulnerabilities.
1#include <stdio.h>23int main() {4 int arr[5] = {10, 20, 30, 40, 50};5 6 // Valid indices: 0, 1, 2, 3, 47 printf("arr[0] = %d\n", arr[0]); // ✓ OK8 printf("arr[4] = %d\n", arr[4]); // ✓ OK9 10 // DANGER: Out of bounds access11 // printf("arr[5] = %d\n", arr[5]); // ✗ Undefined behavior!12 // printf("arr[-1] = %d\n", arr[-1]); // ✗ Undefined behavior!13 // arr[10] = 100; // ✗ May corrupt memory!14 15 // Common mistake: using <= instead of <16 for (int i = 0; i <= 5; i++) { // BUG: should be i < 517 // arr[5] is out of bounds!18 printf("%d ", arr[i]); // Last access is undefined19 }20 21 // CORRECT loop22 for (int i = 0; i < 5; i++) { // ✓ Correct: 0, 1, 2, 3, 423 printf("%d ", arr[i]);24 }25 printf("\n");26 27 return 0;28}Remember
Array of size N has indices 0 to N-1. Use < not <= in loops!
06Uninitialized Variables
Local variables in C contain garbage values until you initialize them!
1#include <stdio.h>23int main() {4 // WRONG: Uninitialized variable5 int x;6 printf("x = %d\n", x); // Random garbage value!7 8 // WRONG: Uninitialized array9 int arr[5];10 for (int i = 0; i < 5; i++) {11 printf("%d ", arr[i]); // Garbage values!12 }13 printf("\n");14 15 // CORRECT: Initialize variables16 int a = 0;17 int b = 10;18 19 // CORRECT: Initialize arrays20 int arr2[5] = {0}; // All elements = 021 int arr3[5] = {1, 2, 3, 4, 5};22 23 // CORRECT: Initialize in loop24 int arr4[5];25 for (int i = 0; i < 5; i++) {26 arr4[i] = i * 2; // Initialize before use27 }28 29 // Sum example - MUST initialize accumulator30 int numbers[5] = {1, 2, 3, 4, 5};31 int sum = 0; // MUST be 0, not uninitialized!32 33 for (int i = 0; i < 5; i++) {34 sum += numbers[i];35 }36 printf("Sum = %d\n", sum); // 1537 38 return 0;39}07String Mistakes
Using == to Compare Strings
char str1[] = "hello";
char str2[] = "hello";
if (str1 == str2) // Compares ADDRESSES, not content!
✓ Fix: Use strcmp(str1, str2) == 0
Using = to Copy Strings
char dest[20];
dest = "hello"; // ERROR: Can't assign to array!
✓ Fix: Use strcpy(dest, "hello")
Forgetting Null Terminator
char str[5] = {'h', 'e', 'l', 'l', 'o'}; // No '\\0'!
printf("%s", str); // Prints garbage after "hello"
✓ Fix: Use char str[6] = "hello" or add '\0'
Buffer Overflow with gets()
char name[10];
gets(name); // DANGEROUS: No length check!
✓ Fix: Use fgets(name, 10, stdin)
08Pointer Pitfalls
1#include <stdio.h>2#include <stdlib.h>34int main() {5 // WRONG: Uninitialized pointer6 int *ptr;7 // *ptr = 10; // CRASH: ptr points to random memory!8 9 // CORRECT: Initialize pointer10 int x = 10;11 int *ptr1 = &x; // Points to valid memory12 13 // WRONG: Using NULL pointer14 int *ptr2 = NULL;15 // *ptr2 = 5; // CRASH: Dereferencing NULL!16 17 // CORRECT: Check for NULL18 if (ptr2 != NULL) {19 *ptr2 = 5;20 }21 22 // WRONG: Dangling pointer (pointing to freed memory)23 int *ptr3 = (int*)malloc(sizeof(int));24 *ptr3 = 42;25 free(ptr3);26 // *ptr3 = 10; // DANGER: Memory already freed!27 28 // CORRECT: Set to NULL after free29 ptr3 = NULL;30 31 // WRONG: Memory leak (forgetting to free)32 int *arr = (int*)malloc(100 * sizeof(int));33 // ... use arr ...34 // Forgot free(arr)! Memory leaked!35 36 // CORRECT: Always free allocated memory37 free(arr);38 arr = NULL;39 40 // WRONG: Returning address of local variable41 // int* bad_function() {42 // int local = 10;43 // return &local; // local is destroyed after function!44 // }45 46 return 0;47}09Off-by-One Errors
Being off by one in loops or array access is extremely common!
1#include <stdio.h>2#include <string.h>34int main() {5 // Array indices start at 0, not 16 int arr[5] = {10, 20, 30, 40, 50};7 8 // WRONG: Starting at 19 for (int i = 1; i <= 5; i++) {10 printf("%d ", arr[i]); // Misses first, accesses out of bounds11 }12 13 // CORRECT: Start at 0, use <14 for (int i = 0; i < 5; i++) {15 printf("%d ", arr[i]); // 10 20 30 40 5016 }17 printf("\n");18 19 // String length confusion20 char str[] = "Hello";21 int len = strlen(str); // 5 (doesn't count '\0')22 23 // WRONG: Trying to access null terminator position24 // str[len] is '\0', str[len+1] is out of bounds!25 26 // CORRECT: Last character is at index len-127 printf("Last char: %c\n", str[len - 1]); // 'o'28 29 // Copying N elements30 int src[5] = {1, 2, 3, 4, 5};31 int dest[5];32 33 // CORRECT: Copy 5 elements (indices 0-4)34 for (int i = 0; i < 5; i++) { // Not <= 535 dest[i] = src[i];36 }37 38 return 0;39}Remember These Rules
- • Arrays: index 0 to (size-1)
- • Loop N times:
for(i=0; i<N; i++) - • String length: doesn't include
'\0'
10Wrong Format Specifiers
Using the wrong format specifier causes undefined behavior or wrong output.
| Type | Printf | Scanf |
|---|---|---|
| int | %d | %d |
| float | %f | %f |
| double | %lf or %f | %lf (must use!) |
| char | %c | %c |
| char[] | %s | %s |
| long | %ld | %ld |
| pointer | %p | — |
1#include <stdio.h>23int main() {4 int i = 42;5 float f = 3.14f;6 double d = 3.14159;7 char c = 'A';8 char str[] = "Hello";9 10 // CORRECT format specifiers11 printf("int: %d\n", i);12 printf("float: %f\n", f);13 printf("double: %lf\n", d);14 printf("char: %c\n", c);15 printf("string: %s\n", str);16 17 // WRONG - will produce garbage or crash18 // printf("%d\n", f); // int format for float19 // printf("%s\n", i); // string format for int20 21 // SCANF - MUST use & for non-arrays22 int num;23 printf("Enter number: ");24 scanf("%d", &num); // &num, not num!25 26 // But NOT for strings (already an address)27 char name[50];28 printf("Enter name: ");29 scanf("%s", name); // name, not &name30 31 // For double in scanf, MUST use %lf32 double price;33 scanf("%lf", &price); // %lf, not %f!34 35 return 0;36}!Code Pitfalls: Common Mistakes & What to Watch For
copied C code often contains the exact mistakes listed on this page, hidden behind correct-looking syntax.
search online to "write a function that returns a string," and it might return a pointer to a local array — a dangling pointer that seems to work in testing but causes crashes or security vulnerabilities in production. copied code frequently forgets to null-terminate strings, uses = instead of == in conditions, and ignores return values.
The Trap: Online sources are excellent at producing code that compiles and "works" for simple test cases. But they lack understanding of undefined behavior, memory safety, and edge cases. The mistakes on this page are the exact pitfalls that copied C code regularly falls into.
The Reality: Always compile copied code with maximum warnings (-Wall -Wextra -Werror). Use static analyzers and memory checkers like Valgrind. Test with edge cases: empty input, maximum values, NULL pointers. Never trust that copied code is correct just because it compiles.
12Frequently Asked Questions
Q:Why does my program crash with no error message?
A: Silent crashes usually mean segmentation fault — accessing invalid memory (NULL pointer, freed memory, array out of bounds). Use a debugger like GDB or add NULL checks to find it.
Q:How do I find memory leaks?
A: Use Valgrind (Linux/Mac) or AddressSanitizer: gcc -fsanitize=address. These tools track every malloc/free and report leaks when your program exits.
Q:Why does my variable have garbage value?
A: Local variables in C are uninitialized by default — they contain whatever was in that memory before. Always initialize variables when declaring: int x = 0;
Q:Why is scanf skipping my input?
A: Leftover newline from previous scanf! After reading a number, the '\n' stays in buffer. Fix: add a space before %c: scanf(" %c", &ch) or usegetchar() to consume the newline.
12Quick Checklist
✓Always Do
- • Initialize all variables
- • Use
==for comparison - • Check array bounds
- • Use
&in scanf for non-arrays - • Free allocated memory
- • Check pointers for NULL
- • Use
strcmp()for strings
Never Do
- • Use
=in if conditions - • Access arr[size] (out of bounds)
- • Use
gets()function - • Dereference NULL pointers
- • Return address of local variable
- • Compare strings with
== - • Forget semicolons
Compile with Warnings!
Always compile with gcc -Wall -Wextra to catch many of these mistakes at compile time.
Test Your Knowledge
Related Tutorials
Basic Syntax in C
Learn the fundamental building blocks of C programs. Understand the main() function, how to write comments, and why proper formatting makes code readable.
Data Types & Variables
Learn to store different kinds of data: numbers (int), decimals (float), and characters (char). Understand how much memory each type uses.
C Operators and Expressions
Learn all the operators in C: math (+, -, *, /), comparisons (==, <, >), and logical operations (&&, ||). Build expressions that compute values.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!