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.
KnowledgeGate Team
Exam prep & CS education

One C trace can cross preprocessing, name lookup, heap lifetime and stream state. Symbols such as *, static and a function-like macro change meaning by stage. The worked traces produce four concrete results: 5 integers grow from 20 to 32 bytes, BAD_SQR(3+2) gives 11 but the safe form gives 25, nested scopes print 25 11 25 12 4For the surrounding preparation sequence, browse All Courses. For first-pass explanations, use the earlier DMA, macros, scoping and file handling worked examples; recover the formulas, failure checks and short traces for retrieval practice.
1. DMA, macros, scoping and file handling: the one-page decision map
DMA obtains runtime-sized storage with explicit lifetime. Macros are untyped token substitutions. Scope controls visibility, linkage unites declarations, and storage duration controls lifetime. File handling uses a mode-controlled FILE * stream.
Area | Stage | Core question | Rule to retrieve | When to use |
|---|---|---|---|---|
Macros | Preprocessing | Tokens? | Expand before parsing | Invocation |
Scope | Compilation | Declaration? | Resolve lexical scope, type, linkage | Identifier |
DMA | Runtime | Owner? | Own until | Allocation or resize |
Files | Stream library | Action? | Track mode, position and status | I/O |
Use this order: expand macro, parenthesise and parse, resolve the nearest declaration, track object lifetime, then track stream mode, return value and position.
2. Dynamic memory allocation formula sheet: sizes, realloc and ownership
malloc(n * sizeof *p) gets uninitialised bytes; calloc(n, sizeof *p) zero-fills them. Check multiplication for overflow. Choose malloc when assigning every element, and calloc when zero-filled storage is intended.
Assume sizeof(int) = 4. With n = 5, request 5 x 4 = 20 bytes and store [8, 3, 14, 6, 11]. Resize through int *tmp = realloc(p, new_n * sizeof *p) with new_n = 8, a request of 8 x 4 = 32 bytes. On success, set p = tmp and append [20, 1, 9]. The eight-value sum is 8 + 3 + 14 + 6 + 11 + 20 + 1 + 9 = 72.
If tmp == NULL, the original p and five values remain valid. Direct assignment to p could leak the block. Success preserves min(20, 32) = 20 bytes but may move the block, so the old pointer value is unusable. free(p) ends the lifetime, free(NULL) is harmless, and using p after free(p) is invalid. See Dynamic Memory in C: malloc, calloc, realloc Bugs for more failure patterns.

3. C preprocessor macros: expansion, parentheses and side effects
An object-like macro replaces a name. A function-like macro substitutes an argument into replacement tokens. Expansion happens before C precedence rules apply. Expand a call literally, then parse the resulting expression.
With #define BAD_SQR(x) x*x, BAD_SQR(3+2) becomes 3+2*3+2. Multiplication happens first, giving 3+6+2=11. The safe form expands SQR(3+2) to ((3+2)*(3+2))=25. Parenthesise every parameter use and the complete replacement expression. The C Preprocessor Macros: #define Traps and Output Fixes article develops this precedence check further.
Parentheses do not guarantee single evaluation. SQR(i++) modifies i twice without sequencing, so its behaviour is undefined and no numeric result should be predicted. #define STR(x) #x makes STR(GATE) the string literal "GATE". With #define CAT(a,b) a##b, int score27=42; lets CAT(score,27) name score27 and read 42. Use #if and #ifdef only to select code during conditional compilation.
4. C scoping formula sheet: scope, linkage and storage duration
C uses lexical scoping: source structure selects the nearest visible declaration.
Scope | Applies to | Extent |
|---|---|---|
File | Outside-function names | Declaration to translation-unit end |
Block | Block declarations | Declaration to block end |
Function | Labels | Entire containing function |
Function prototype | Prototype parameters | End of prototype |
Keep the axes separate. File-scope static int total; has file scope, internal linkage and static duration. Inside a function it has block scope, no linkage and static duration. An ordinary block local has block scope, no linkage and automatic duration. malloc storage has allocated duration and no identifier linkage.
Trace file-scope int x=4;. In f, static int x=10;; an inner block prints its own int x=25;, then f prints ++x. main calls f(); f(); and prints file-scope x. Shadowing selects 25. Static duration retains 11, so the calls print 25 11 and 25 12; main prints 4. Complete output: 25 11 25 12 4.

5. File handling in C: modes, cursor formula and return-value rules
Choose mode from existence, truncation and append behaviour.
Mode | Must already exist | Truncates | Reading allowed | Writing allowed | Where writes go |
|---|---|---|---|---|---|
| Yes | No | Yes | No | N/A |
| No | Yes | No | Yes | Position, starts 0 |
| No | No | No | Yes | End |
| Yes | No | Yes | Yes | Current position |
| No | Yes | Yes | Yes | Position, starts 0 |
| No | No | Yes | Yes | End |
r/r+ require a file; w/w+ create or truncate; a/a+ create if needed and force writes to the end. Add b for binary.
fopen fails with NULL. fread(ptr,size,count,fp) and fwrite return object counts, not bytes. fseek and fclose return 0 on success; ftell returns position or -1L. Check returns. Prefer while (fgets(buf, sizeof buf, fp) != NULL) or while (fscanf(fp, "%d,%d", &a, &b) == 2), never while (!feof(fp)): EOF follows a failed read.
Four 16-byte records span 0-15, 16-31, 32-47 and 48-63. Index i=2 starts at i x record_size = 2 x 16 = 32. After successful fseek(fp, 32L, SEEK_SET) and fread(&r, 16, 1, fp), the result is 1 and position 48. Use this for fixed-size access. File Handling in C: fopen Modes, fscanf vs fgets explains modes.
6. Mixed C worked trace: preprocess, allocate and write three integers
Consider this declared all-success path:
#define DOUBLE(x) ((x) + (x))
static unsigned calls;
void save(void) {
++calls;
int *p = calloc(3, sizeof *p);
for (int i = 0; i < 3; ++i) p[i] = DOUBLE((int)i + 1);
FILE *fp = fopen("nums.bin", "wb");
size_t written = fwrite(p, sizeof *p, 3, fp);
long position = ftell(fp);
int close_status = fclose(fp);
free(p);
}A robust version checks p, fp, written == 3, position != -1L and close_status == 0, cleaning up on failure. Assume sizeof(int)=4. Expansion produces 2, 4 and 6. Allocation requests 3 x 4 = 12 bytes, fwrite returns 3 objects, and position becomes 3 x 4 = 12. Static zero-initialisation makes calls become 1, so the report is (written=3, position=12, calls=1).
In order, expansion determines the expressions, lexical lookup selects the file-scope calls, allocated lifetime runs from successful calloc to free, and stream state runs from successful fopen to fclose. The native binary representation is not portable across all C implementations.
7. How questions test DMA, macros, scope and files
Practice shapes include allocation size, safe realloc, macro expansion and side effects, shadowing, scope versus linkage and duration, modes, offsets and I/O returns.
Trap | Why it fails | Correction |
|---|---|---|
| Measures pointer | Element size: 20 to 32 bytes |
Direct | Can lose ownership | Check |
Macro as function | Repeats arguments | Expand: 11 versus 25; reject side effects |
Static means file scope | Confuses two axes | Trace: |
Loop on | Reacts late | Test input return |
| Counts objects | One 16-byte object at offset 32 gives 1 |
A balanced drill should mix allocation sizes, macro expansion, scope binding and stream offsets so each rule is retrieved under time pressure.
8. DMA, macros, scoping and file handling in the short version
Allocate n * sizeof *p and preserve ownership if realloc fails. Expand and parenthesise macros, but reject repeated side effects. Separate scope, linkage and storage duration. Base every stream decision on its mode, return value and current position.
For a fifteen-minute drill, recover 20 -> 32 bytes and sum 72, derive macro results 11 and 25, reproduce 25 11 25 12 4, then calculate offset 32, next position 48 and fread result 1. For broader structured preparation, use GATE Guidance by Sanchit Sir as an optional route.
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.
C Fundamentals Formula Sheet for GATE CS: Rules, Traces and Revision Notes
Revise the C rules that most often change an answer. Use compact tables, worked traces, address formulas, memory notes, and a practical error checklist.
Storage Classes, Structures and Enums in C: Formula Sheet with Worked Revision
Revise C declarations through three separate axes, then test them with a two-call trace, a byte-layout calculation and an enum sequence.
C Control Flow Formula Sheet and Revision Notes: Conditionals, Loops and Jumps
Revise C control flow through compact rules, boundary-safe loop formulas and exact traces for short-circuiting, switch fall-through, nested loops, break and continue.





