Why your C program prints garbage: uninitialised variables, explained once
Every batch of first-year C students hits the same bug, and it looks like the compiler is broken. It is not. Here is what is happening, from the HTTP and C guides I uploaded.
In C, declaring a variable does not give it a value. int total; reserves a box of memory the size of an int, and whatever bits were already in that memory are what the box holds. On your laptop that might happen to be zero, so the program looks fine. On the lab machine, or after you add one more function, it is 3241197 or a negative number, and your loop runs forever.
The rule: every variable gets a value before it is read. Not most. Every. int total = 0; int count = 0; char name[50] = ""; If you cannot decide what the value should be at the declaration, you have not understood what the variable is for yet, and that is the actual problem.
Three places this hides:
-
Accumulators. sum, total, count, product. If the first line inside the loop is sum += x, then sum needed to be 0 before the loop. product needs 1, not 0.
-
Arrays. int marks[10]; is ten boxes of garbage. If you fill only the first five and then print all ten, the last five are noise. Either fill them all or track how many are valid.
-
Pointers. int *p; then *p = 5; writes 5 to a random address. Sometimes it crashes, sometimes it silently corrupts something else, which is worse. A pointer starts as NULL or as the address of something real.
How to catch it before the examiner does: compile with warnings on. gcc -Wall -Wextra tells you 'may be used uninitialized' at the exact line. Students switch warnings off because the output is noisy. The noise is the bug list.
One last thing. Global variables and static variables are initialised to zero automatically. Local variables are not. That inconsistency is the whole reason this bug exists, and knowing it is worth more than any trick.
0 Comments
Loading comments…