C Dynamic Memory Allocation, Macros, Scope and File Handling: 10 Mistakes
Trace ten common C mistakes from incorrect allocation sizes to broken file-reading loops. Each diagnosis shows why it happens, the exact failure and the safer repair.
KnowledgeGate Team
Exam prep & CS education

These C questions are rarely lost because malloc, #define, scope or fopen is unknown. They are lost because the solver silently assumes a byte count, evaluation order, name binding or stream state that the program never guarantees. Each failure has a concrete cause: a byte count mistaken for an element count, an unsequenced macro argument, a name resolved from the wrong scope, or a stream read tested too late. For a full four-topic execution map and worked examples, read Dynamic Memory Allocation, Macros, Scoping and File Handling in C: Worked Examples; this post isolates ten exam mistakes and their repairs. Use CS Fundamentals for Exams & Placements as the wider subject route.
1. Mistakes 1 and 2: allocation size and uninitialised memory
Mistake 1, allocating elements as bytes. Why it happens: n is treated as an element count and a byte count. On a model where sizeof(int) = 4, size_t n = 6; int *p = malloc(n); allocates 6 bytes, while six integers require 6 x 4 = 24 bytes. p[0] occupies bytes 0..3; p[1] needs bytes 4..7, beyond the allocation. This is undefined behaviour. Do instead: use int *p = malloc(n * sizeof *p); and check p != NULL before dereferencing.
Mistake 2, assuming malloc returns zeroed integers. Why it happens: fresh memory is confused with initialised memory. Reading p[0] before a store is undefined behaviour. Do instead: initialise the entries as 3, 6, 9, 12, 15, 18, whose sum is 63, or use calloc(n, sizeof *p) when zeros are intended. Use a C programming course for a syntax reset.
2. Mistake 3: overwriting the only pointer with realloc
Mistake 3, assigning realloc directly to its owner. Why it happens: direct assignment looks harmless. With sizeof(int) = 4, p owns 16 bytes containing {10, 20, 30, 40}; realloc(p, 8 * sizeof *p) requests 32 bytes.
What goes wrong: on NULL, the original 16 bytes with four values remain allocated, but direct assignment loses their pointer, causing a leak; realloc did not free it. After a move, never dereference an old alias.
Do instead: use int *tmp = realloc(p, 8 * sizeof *p);. On failure, retain p and handle the error. On success, set p = tmp, preserve the first four values, and set p[4..7] to {50, 60, 70, 80}. Now 10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 = 360. Call free(p) once.

3. Mistakes 4 and 5: expand the macro before reading it
Mistake 4, missing parentheses. Why it happens: SQUARE(2 + 3) is read like a function call. With #define SQUARE(x) x*x, substitution gives 2 + 3 * 2 + 3. Multiplication happens, so the value is 2 + 6 + 3 = 11, not 25. Do instead: use #define SQUARE(x) ((x) * (x)); the call becomes ((2 + 3) * (2 + 3)) = 25.
Mistake 5, passing a side effect to a repeated parameter. Why it happens: the parenthesised macro looks safe. But int i = 4; int y = SQUARE(i++); expands to ((i++) * (i++)). It modifies i twice without sequencing, so behaviour is undefined. Do not calculate y or final i. Do instead: use static inline int square(int x) { return x * x; }. Then square(i++) returns 16 after one evaluation and leaves i = 5. C Preprocessor Macros gives the trace.
4. Mistakes 6 and 7: scope is not storage duration
Mistake 6, importing the caller's scope. Why it happens: a called function seems to see the nearest stack value. Given int score = 10;, void show(void) { printf("%d ", score); }, and void caller(void) { int score = 20; show(); printf("%d", score); }, caller() prints 10 20, not 20 20. show uses file-scope score; caller uses block scope. Do instead: resolve names where defined, draw scope boxes, and pass the intended caller value.
Mistake 7, resetting a static local. Why it happens: block scope is confused with automatic lifetime. Inside tick(), static int count = 2; count += 3; prints 5 8 11 across three calls. An ordinary int count = 2; prints 5 5 5. Do instead: track scope and storage duration in separate columns.
5. Mistake 8: choose fopen mode from intent

Mistake 8, opening output with "w" by habit. Why it happens: mode strings become boilerplate. In a POSIX-style example where each \n is one byte, let marks.txt contain exactly 72\n81\n, or 6 bytes. After successful fopen("marks.txt", "w"), the file is truncated before the first fprintf. Writing 90\n leaves only 3 bytes, and changing later code cannot recover the earlier records.
Do instead: to add one mark at the end, use "a", check fp != NULL, and check relevant write and close results. The file becomes exactly 72\n81\n90\n, which is 9 bytes under the same model. "w+" also truncates; "a+" still directs writes to the end.
6. Mistakes 9 and 10: let each read control the loop
Mistake 9, testing EOF too early. Why it happens: EOF is treated as a prediction, not a failed-read flag. For 12 7 5, start with int x; int sum = 0;. Three fscanf calls store 12, 7, and 5, giving 24. Before a fourth read, feof(fp) is false. That read returns EOF and leaves x = 5; adding again gives 29. Do instead: while (fscanf(fp, "%d", &x) == 1) sum += x; ends at 24. With 12 X 5, return 0 signals malformed input.
Mistake 10, mixing token and line reads. Why it happens: consuming a number is mistaken for consuming its line. Given 42\nAda Lovelace\n, fscanf(fp, "%d", &id) stores 42 but leaves \n; the next fgets reads "\n". Do instead: call fgetc until \n or EOF, then fgets reads "Ada Lovelace\n" After these corrected loops, test both the numeric and line-oriented cases.
7. DMA, macros, scope and file handling: the 60-second audit
Audit five points: allocation bytes from count and type; original ownership until realloc succeeds; macro expansion before evaluation; scope versus lifetime; and read-result-controlled file loops. Recheck the anchors: six four-byte integers need 24 bytes, eight resized values sum to 360, the bad square macro gives 11, the scope trace prints 10 20, and the correct file sum is 24, not 29. Use C Language: Concepts, MCQs, Coding Questions as the structured next step after this audit. For a compact revision map and mixed trace, use the DMA, macros, scoping and file handling formula sheet; this post stays with mistake diagnosis and repair.
Keep learning
Dynamic Memory Allocation, Macros, Scoping and File Handling in C: Worked Examples
Trace four C concepts through code: grow an array without losing ownership, expand macros safely, resolve shadowed names, and process file records by return status.
DMA, Macros, Scoping and File Handling in C: Formula Sheet with Worked Revision Notes
Build a compact C revision sheet for dynamic memory, macros, scope, linkage, storage duration and file streams. Four worked checks connect each rule to an exact result.
Dynamic Memory Allocation in C: malloc, calloc, realloc and the Bugs Exams Test
Follow one resizable integer array from allocation to release. The worked trace explains byte counts, preserved values, uninitialised elements and the safe temporary-pointer pattern.
Dynamic Memory Allocation in C: malloc, calloc, realloc and free with a Worked Example
A runnable marks example shows how C requests, initializes, grows and releases runtime storage, with checked byte counts, ownership and safe realloc handling.





