Fundamentals 14 min read

5 Common C Bugs Every Programmer Should Avoid

This article highlights five typical C programming mistakes—uninitialized variables, array out‑of‑bounds access, string overflows, double freeing memory, and invalid file pointers—explains why they occur, shows sample code and outputs, and offers practical tips to prevent each bug.

Java Backend Technology
Java Backend Technology
Java Backend Technology
5 Common C Bugs Every Programmer Should Avoid

Computer science students often learn C as the ancestor of many high‑level languages; mastering it deepens understanding of computer principles, operating systems, and memory management. Even experienced programmers can fall into common pitfalls, which this article enumerates and demonstrates.

1. Uninitialized Variables

When a program starts, the system allocates memory for variables, but if a variable is not explicitly initialized its value may be arbitrary. Some environments zero‑initialize memory, but relying on that harms portability. Initializing variables is a good habit.

#include <stdio.h>
#include <stdlib.h>

int main() {
  int i, j, k;
  int numbers[5];
  int *array;

  puts("These variables are not initialized:");
  printf("  i = %d
", i);
  printf("  j = %d
", j);
  printf("  k = %d
", k);

  puts("This array is not initialized:");
  for (i = 0; i < 5; i++) {
    printf("  numbers[%d] = %d
", i, numbers[i]);
  }

  puts("malloc an array ...");
  array = malloc(sizeof(int) * 5);

  if (array) {
    puts("This malloc'ed array is not initialized:");
    for (i = 0; i < 5; i++) {
      printf("  array[%d] = %d
", i, array[i]);
    }
    free(array);
  }

  puts("Ok");
  return 0;
}

Running this program on a typical PC yields random values for some variables and array elements, while other values happen to be zero. Different operating systems produce different results, illustrating the need for explicit initialization.

2. Array Out‑of‑Bounds Access

Arrays are zero‑based; accessing an index equal to the length overruns the buffer. The following example intentionally reads beyond the five‑element array, showing that the first five values are correct but the rest are garbage, and that writing beyond bounds can cause a crash.

#include <stdio.h>
#include <stdlib.h>

int main() {
  int i;
  int numbers[5];
  int *array;

  puts("This array has five elements (0 to 4)");
  for (i = 0; i < 5; i++) {
    numbers[i] = i;
  }
  for (i = 0; i < 10; i++) {
    printf("  numbers[%d] = %d
", i, numbers[i]);
  }

  puts("malloc an array ...");
  array = malloc(sizeof(int) * 5);
  if (array) {
    puts("This malloc'ed array also has five elements (0 to 4)");
    for (i = 0; i < 5; i++) {
      array[i] = i;
    }
    for (i = 0; i < 10; i++) {
      printf("  array[%d] = %d
", i, array[i]);
    }
    free(array);
  }

  puts("Ok");
  return 0;
}

Reading beyond the allocated range yields unpredictable values; writing beyond it can trigger a core dump.

3. String Overflow

In C, a string is an array of char. Using unsafe functions such as gets allows the user to write more characters than the buffer can hold, corrupting adjacent memory. The example below reads a name into a ten‑character buffer; a short input works, but a long input overwrites the variables var1 and var2 and may cause a segmentation fault.

#include <stdio.h>
#include <string.h>

int main() {
  char name[10];
  int var1 = 1, var2 = 2;

  printf("var1 = %d; var2 = %d
", var1, var2);
  puts("Where do you live?");
  gets(name);
  printf("<%s> is length %d
", name, strlen(name));
  printf("var1 = %d; var2 = %d
", var1, var2);
  puts("Ok");
  return 0;
}

Using a safe alternative such as getline prevents this overflow.

4. Double Freeing Memory

Memory allocated with malloc must be released exactly once with free. Calling free twice on the same pointer leads to undefined behavior and often a core dump. The following program demonstrates this error.

#include <stdio.h>
#include <stdlib.h>

int main() {
  int *array;
  puts("malloc an array ...");
  array = malloc(sizeof(int) * 5);
  if (array) {
    puts("malloc succeeded");
    puts("Free the array...");
    free(array);
  }
  puts("Free the array...");
  free(array); // double free
  puts("Ok");
}

To avoid double frees, encapsulate allocation and deallocation in dedicated functions or set the pointer to NULL after freeing.

5. Invalid File Pointer

When opening a file with fopen, the function returns NULL if the file does not exist or cannot be opened. Using the returned pointer without checking leads to a segmentation fault. The example below omits the check and crashes when FILE.TXT is missing.

#include <stdio.h>

int main() {
  FILE *pfile;
  int ch;

  puts("Open the FILE.TXT file ...");
  pfile = fopen("FILE.TXT", "r");
  puts("Now display the contents of FILE.TXT ...");
  while ((ch = fgetc(pfile)) != EOF) {
    printf("<%c>", ch);
  }
  fclose(pfile);
  puts("Ok");
  return 0;
}

Always verify that the file pointer is not NULL before reading or writing.

Conclusion

Even seasoned developers can fall into these five classic C bugs. By adopting disciplined habits—initializing variables, respecting array bounds, using safe string input functions, freeing memory exactly once, and validating file pointers—programmers can avoid many serious errors and produce more robust C code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

C programmingInitializationcommon bugsarray bounds
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.