📖 Scenario: Imagine you are writing a small program in C that creates a dynamic array to store some numbers. After using the array, you need to clean up the memory to keep your program healthy and avoid memory leaks.
🎯 Goal: You will create a dynamic array using malloc, then use the free function to release the memory when you are done.
📋 What You'll Learn
Create a pointer variable to hold dynamically allocated memory for an array of integers
Allocate memory for 5 integers using malloc
Use the free function to release the allocated memory
Print a message confirming the memory has been freed
💡 Why This Matters
🌍 Real World
Dynamic memory management is important in programs that need flexible storage, like games, databases, or any software handling variable data sizes.
💼 Career
Understanding how to allocate and free memory safely is a key skill for C programmers working in systems programming, embedded systems, or performance-critical applications.
Progress0 / 4 steps
1
Create a pointer for dynamic memory
Declare a pointer variable called numbers of type int * and set it to NULL.
C
Hint
Use int *numbers = NULL; to declare a pointer that points to nothing yet.
2
Allocate memory for 5 integers
Use malloc to allocate memory for 5 integers and assign it to the pointer numbers.
C
Hint
Use malloc(5 * sizeof(int)) to allocate space for 5 integers.
3
Free the allocated memory
Use the free function to release the memory pointed to by numbers.
C
Hint
Call free(numbers); to release the memory.
4
Print confirmation message
Write a printf statement to display the message "Memory has been freed.".
C
Hint
Use printf("Memory has been freed.\n"); to show the message.
Practice
(1/5)
1. What is the main purpose of the free function in C?
easy
A. To initialize a pointer to NULL
B. To allocate new memory dynamically
C. To copy data from one memory location to another
D. To release memory previously allocated by malloc or similar functions
Solution
Step 1: Understand what free does
The free function releases memory that was allocated dynamically, returning it to the system.
Step 2: Differentiate from other memory functions
malloc allocates memory, free releases it. Copying or initializing pointers is unrelated.
Final Answer:
To release memory previously allocated by malloc or similar functions -> Option D