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 |
Read 4 marks, highest = 94
malloc program चलते समय (run time) memory माँगता है - जितनी ज़रूरत हो उतनी। यह memory heap से आती है और तब तक रहती है जब तक आप free() न करें। free भूल जाना memory leak कहलाता है - लंबे चलने वाले programs (servers) धीरे-धीरे पूरी memory खा जाते हैं।
calloc and realloc#
calloc: 0 0 0 after realloc: 10 20 30 40 50
Common dynamic-memory bugs:
- using memory after
free(dangling pointer), - calling
freetwice 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.
(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 |
Aarav 82 Diya 91 Kabir 77 3 records read
Reading line by line and appending#
1 | Session 1: C basics 2 | Session 2: Pointers 3 | Session 3: Files
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/callocallocate heap memory at run time;reallocresizes;freereleases.- Check every allocation for
NULL; free exactly once; set freed pointers toNULL. - Files:
fopen→fprintf/fputsorfscanf/fgets→fclose. "w"erases,"a"appends,"r"reads.