DEV Community

Yunus Emre Güzel
Yunus Emre Güzel

Posted on Edited on Originally published at blog.emreguzel.ca

Why Your C Program Prints a Garbage Value (and How to Fix It)

The Problem: Your printf Shows a Random Number

You declare a variable, print it before assigning anything, and get a number that looks like it came from nowhere:

#include <stdio.h>

int main(void) {
    int total;
    printf("Total: %d\n", total);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Run it and you might see Total: 32764. Run it again and it might say Total: -1073745472. Change nothing, rebuild, and it can be a third number.

That is a garbage value: whatever happened to be sitting in that memory before your program claimed it. It is not random in the sense of being generated — it is leftover data from something that ran earlier.

Why It Happens: Memory Is Not Cleaned for You

When you write int total;, C reserves four bytes for it. That is all it does. It does not write zero into them.

Those four bytes already have a value — whatever the previous owner left there. Your program, the C runtime, or the operating system used that memory a moment ago. C hands it to you as-is because zeroing every variable would cost time, and C is built to be fast.

So the number you see is real data, just not yours. That is why it changes between runs: the memory layout differs each time.

The Fix: Initialise When You Declare

Give the variable a value at the moment you create it:

int total = 0;
double average = 0.0;
char grade = '\0';
Enter fullscreen mode Exit fullscreen mode

Now printf("Total: %d\n", total); prints Total: 0 every time, on every machine.

This is not optional politeness. It is the difference between a program that works and one that works on your computer today.

The Trap That Bites Harder: Uninitialised Arrays

A single uninitialised int prints a wrong number. An uninitialised char array can print a whole page of junk, or crash:

char name[20];
printf("Name: %s\n", name);   // prints junk until it finds a 0 byte
Enter fullscreen mode Exit fullscreen mode

%s keeps printing characters until it hits a null terminator ('\0'). Your array has no terminator, so printf walks straight past the end of it and keeps going through whatever memory follows. Sometimes you get gibberish. Sometimes you get a segmentation fault.

Fix it the same way:

char name[20] = "";          // first byte is '\0', so %s prints nothing
char buffer[100] = {0};      // every byte zeroed
Enter fullscreen mode Exit fullscreen mode

= {0} is the idiom worth remembering. It zeroes the entire array, not just the first element.

malloc Hands You Garbage Too

malloc reserves memory and leaves whatever was already there. It is the heap version of int total;. calloc reserves the same space and fills it with zeros.

int *a = malloc(5 * sizeof *a);   // contents are indeterminate
int *b = calloc(5, sizeof *b);    // contents are all zero
Enter fullscreen mode Exit fullscreen mode

Use malloc when you are about to write every element anyway. Use calloc when you want zeros. The mistake to avoid is reading from a malloced block before you have written to it. Printing a[0] right after the call can show anything, and it can show something different on another machine.

Structs: Initialise the Whole Thing

Declaring a struct without a value leaves every field as garbage, the same as a plain int. Put = {0} after it and every field becomes zero.

struct Point p1;               // x and y are garbage
struct Point p2 = {0};         // x and y are both 0
struct Point p3 = { .x = 5 };  // x is 5, y is 0
Enter fullscreen mode Exit fullscreen mode

In the last line you only named x. Every field you skip is set to zero, so you do not have to list them all.

Why Globals and Statics Are Fine

Variables declared outside any function, and variables marked static, start at zero. Only plain local variables start with leftovers. That is why the same habit works in one place and prints junk in another.

int counter;               // global: starts at 0

int main(void) {
    static int calls;      // static: starts at 0
    int local;             // plain local: garbage until you set it
    /* ... */
}
Enter fullscreen mode Exit fullscreen mode

It is also why a small test program sometimes "works". A global that happens to start at zero can hide a missing initialisation on the local variable next to it.

Why the Compiler Sometimes Warns and Sometimes Doesn’t

With warnings on, GCC and Clang usually catch this:

gcc -Wall -Wextra -o program program.c
Enter fullscreen mode Exit fullscreen mode

You get:

warning: 'total' is used uninitialized [-Wuninitialized]
Enter fullscreen mode Exit fullscreen mode

But the warning is not guaranteed. If the variable is passed to another function, or its use is behind a condition the compiler cannot follow, the warning disappears and the bug ships.

That is why -Wall -Wextra is a habit, not a guarantee. It catches the obvious cases. It will not catch all of them.

Finding It When the Compiler Stays Quiet

Two tools find what the compiler misses:

Valgrind (Linux, macOS) reports reads of uninitialised memory at runtime:

valgrind --track-origins=yes ./program
Enter fullscreen mode Exit fullscreen mode

You get a line naming the exact variable and the line number where it was read before being written.

AddressSanitizer works on Windows too, through GCC or Clang:

gcc -fsanitize=address -g -o program program.c
./program
Enter fullscreen mode Exit fullscreen mode

It is faster than Valgrind and catches out-of-bounds reads as well — which is what the uninitialised char array above actually is.

The Related Bug You Will Meet Next

Garbage values and scanf problems tend to appear in the same program, because both come from not controlling what is in memory. If your scanf is skipping input or looping forever, that is a separate cause with a separate fix:

A Short Checklist

  • Give every local variable a value on the line where you declare it.
  • Use = {0} for arrays and structs.
  • Use calloc if you want zeroed heap memory, and never read malloced memory before writing to it.
  • Compile with -Wall -Wextra and read the warnings.
  • If the output still looks wrong, run the program under Valgrind or AddressSanitizer.

The Rule, Stated Once

In C, a variable has a value the moment it exists — you just did not choose it.

Initialise every variable when you declare it. Use = {0} for arrays. Compile with -Wall -Wextra. Reach for Valgrind or AddressSanitizer when the compiler says nothing but the output looks wrong.

The habit costs one line per variable and removes an entire class of bug that is otherwise almost impossible to reproduce.


Originally published on my blog. I post new C, Python and AI-agent guides there regularly.

Top comments (0)