⚡0 XP🔥0

Dynamic Memory and File Handling

Lesson 12 of 13 ⏱ 5 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs C

Allocate memory at run time with malloc, calloc, realloc and free, avoid memory leaks, and read/write text files with fopen, fprintf, fscanf and fgets.

Why dynamic memory?#

int a[100]; reserves memory at compile time. But often you only know the size at run time - the number of students in a file, the size of an image. Dynamic allocation asks the operating system for memory while the program runs. This memory comes from the heap and stays until you release it.

Function (in <stdlib.h>) What it does
malloc(bytes) allocate a block, contents uninitialised
calloc(count, size) allocate count elements, all set to 0
realloc(ptr, new_bytes) grow or shrink an existing block (may move it)
free(ptr) give the block back
▶ Try it YourselfC
Ctrl + Enter to run
Output
Read 4 marks, highest = 94
हिंदी में समझें

malloc program चलते समय (run time) memory माँगता है - जितनी ज़रूरत हो उतनी। यह memory heap से आती है और तब तक रहती है जब तक आप free() न करें। free भूल जाना memory leak कहलाता है - लंबे चलने वाले programs (servers) धीरे-धीरे पूरी memory खा जाते हैं।

calloc and realloc#

▶ Try it YourselfC
Ctrl + Enter to run
Output
calloc: 0 0 0
after realloc: 10 20 30 40 50
Common Mistake

Common dynamic-memory bugs:

  • using memory after free (dangling pointer),
  • calling free twice on the same pointer,
  • forgetting free (leak),
  • writing a = realloc(a, ...) directly - if realloc fails it returns NULL and you lose the original block. Use a temporary pointer as above.

A growing list with realloc#

This is how dynamic arrays (like Python lists or C++ vectors) work inside: double the capacity whenever it is full.

▶ Try it YourselfC
Ctrl + Enter to run
Output
(grew capacity to 4)
(grew capacity to 8)
Stored 6 numbers: 5 8 13 21 34 55

File handling#

Variables disappear when the program ends. Files keep data permanently. The steps are always: open → read/write → close.

FILE *fp = fopen("data.txt", "w");   // returns NULL if it fails
fprintf(fp, "...");                  // write
fclose(fp);                          // close (flushes data to disk)
Mode Meaning
"r" read (file must exist)
"w" write - creates the file or erases an existing one
"a" append - write at the end
"r+" read and write
"rb", "wb" binary read / write
▶ Try it YourselfC
Ctrl + Enter to run
Output
Aarav  82
Diya   91
Kabir  77
3 records read

Reading line by line and appending#

▶ Try it YourselfC
Ctrl + Enter to run
Output
1 | Session 1: C basics
2 | Session 2: Pointers
3 | Session 3: Files
Tip

Always check that fopen did not return NULL (wrong path, no permission, file missing in "r" mode), and always fclose. Unclosed files may lose data that was still waiting in the buffer.

Summary#

  • malloc/calloc allocate heap memory at run time; realloc resizes; free releases.
  • Check every allocation for NULL; free exactly once; set freed pointers to NULL.
  • Files: fopen → fprintf/fputs or fscanf/fgets → fclose.
  • "w" erases, "a" appends, "r" reads.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Dynamic array average

Read n, allocate an int array of size n with malloc, read n numbers, print Average = 41.20 (2 decimals) and free the memory.

Test input:
5
12 45 67 23 59
Expected output:
Average = 41.20
2

Write and read back a file

Write the numbers 1 to 5, one per line, into nums.txt. Close it, open it again for reading, add the numbers with fscanf, and print Sum from file = 15.

Expected output:
Sum from file = 15

Quick Quiz

Q1.

What does malloc return if it cannot allocate memory?

Q2.

What is the difference between malloc(n * sizeof(int)) and calloc(n, sizeof(int))?

Q3.

What is a memory leak?

Q4.

Which mode opens a file for adding to the end without erasing it?