π§
STUDENT NOTES Β· C & C++ WEEK 5 OF 8
Renting Memory & Keeping Records π§
Arrays have fixed sizes β but what if you don't know the size until runtime? Time to RENT memoryβ¦ and always return it.
1malloc β renting memory at runtime
βοΈ
Chip: malloc rents you raw bytes from the heap and hands back a POINTER (Week 4 pays off!). You choose the size while the program runs.
2free β ALWAYS return what you rent
π
Bugly: Rent memory in a loop and never free it? The program eats RAM until the machine begs for mercy. A memory leak β my slowest, cruelest attack. Hehehe.
π¦
Professor Hoot: Golden rule: every malloc has a matching free. Python's garbage collector spoiled you β in C, YOU are the garbage collector.
3Files in C
βοΈ
Chip: Same ideas as Python's Day 13 β "w" writes, "r" reads, "a" appends β with fopen/fclose doing the ceremony. And ALWAYS check for NULL: the file might not exist.
4Sorting sets up searching
π€
Bittu: Binary search finds 1 number among a MILLION in ~20 looks β but only on a SORTED array. Sort first, search fast. Class covers the classic sorts live.
5Quick quiz! π§
You malloc memory in a loop and never call free. What happens?
π‘ Nothing frees itself in C. Leaks build until the OS steps in. Every malloc needs its free.
fopen("data.txt", "r") on a missing file returnsβ¦
π‘ Read mode needs the file to exist; on failure fopen returns NULL. Dereference NULL andβ¦ segfault city.
6Your mission π
Mission 1: malloc space for 5 ints, fill them with squares (1,4,9,16,25), print, then free.
Mission 2: Write your 3 favourite games to games.txt with fprintf, then read them back with fgets.
Mission 3: Open a file that doesn't exist and print a friendly message when fopen gives NULL.
Week 5 complete β Month 1 of C conquered! π
Next: C++ enters β classes, objects and cout. Same engine, shinier body.
Go to Week 6: Hello C++ β