RisingCoder Full course β†’
Week 1Week 2Week 3Week 4Week 5Week 6Week 7Week 8🐍 Python notes
🧠
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++ β†’

βš”οΈ Or test yourself in the C & C++ Arcade β†’