Lesson 21 of 23

Dynamic Memory: malloc and free

10 min 35 XP

When the size is only known at run time, ask for heap memory with malloc. Release it with free when you're done, or you leak memory.

Example: edit me and press Run

Output Loading C (first time takes a few seconds)
Press Run to see the result here.

malloc vs calloc: calloc also zeroes the memory; realloc resizes it. Stack vs heap is a frequent interview question.

Challenge

+35 XP

Read n, allocate an array of n ints with malloc, fill it with the first n Fibonacci numbers (0, 1, 1, 2, ...), print them separated by spaces, then free it. Input: 7 → Output: 0 1 1 2 3 5 8

Output Loading C (first time takes a few seconds)
Press Run to see the result here.