Lesson 21 of 23

Dynamic Memory: malloc மற்றும் freeDynamic Memory: malloc and free

10 min 35 XP

Array அளவு run நேரத்தில் மட்டுமே தெரிந்தால் malloc மூலம் heap-ல் memory கேட்கலாம். பயன்பாடு முடிந்தவுடன் free செய்ய வேண்டும்; இல்லையெனில் memory leak.

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 memory-ஐ 0 ஆக்கும். realloc அளவை மாற்றும். Stack vs heap வேறுபாடு interview-ல் அடிக்கடி கேட்கப்படும்.

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

Challenge

+35 XP

n-ஐப் படித்து, malloc மூலம் n அளவு array உருவாக்கி, முதல் n Fibonacci எண்களை (0, 1, 1, 2, ...) அதில் சேமித்து space விட்டு print செய்யுங்கள். பிறகு free செய்யுங்கள். Input: 7 → Output: 0 1 1 2 3 5 8

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.