Freeing Memory with free()
Part of the Logic & Flow section of Coddy's C journey — lesson 35 of 63.
When you allocate memory dynamically using malloc(), that memory remains allocated until you explicitly release it. The free() function is your tool for returning dynamically allocated memory back to the system when you're finished using it.
The free() function takes one argument: a pointer to the memory block you want to deallocate. This must be the same pointer that was returned by malloc() (or related functions like calloc()).
#include <stdlib.h>
int *ptr = (int*)malloc(sizeof(int)); // Allocate memory
*ptr = 42; // Use the memory
free(ptr); // Free the memory when doneFailing to call free() creates what's known as a memory leak. The allocated memory remains reserved by your program even though you're no longer using it. In long-running programs or programs that allocate memory repeatedly, these leaks can consume all available system memory and cause performance problems or crashes.
Remember: every malloc() should have a corresponding free(). This pairing is essential for responsible memory management in C programming.
Challenge
EasyWrite a C program that demonstrates the complete lifecycle of dynamic memory allocation and deallocation. Your program should:
- Read an integer
countfrom the user representing how many integers to store - Use
malloc()withsizeof()to dynamically allocate memory for an array ofcountintegers - Check if the memory allocation was successful - if it fails, print
Memory allocation failed!and terminate the program - If allocation succeeds, print
Memory allocated successfully! - Read
countinteger values from the user and store them in the allocated array - Calculate and print the sum of all values in the format:
Sum: [value] - Find and print the maximum value in the format:
Maximum: [value] - Use
free()to deallocate the memory - Print
Memory freed successfully!to confirm the cleanup
Remember to include the <stdlib.h> header to use malloc() and free(). This challenge demonstrates the essential pairing of malloc() and free() to prevent memory leaks in your programs.
For example, if the input is:
4
15 8 23 12Your output should be:
Memory allocated successfully!
Sum: 58
Maximum: 23
Memory freed successfully!This challenge reinforces the critical concept that every dynamically allocated block of memory must be properly freed when no longer needed, completing the responsible memory management cycle in C programming.
Cheat sheet
Use free() to deallocate memory that was allocated with malloc():
#include <stdlib.h>
int *ptr = (int*)malloc(sizeof(int)); // Allocate memory
*ptr = 42; // Use the memory
free(ptr); // Free the memory when doneEvery malloc() should have a corresponding free() to prevent memory leaks. The pointer passed to free() must be the same pointer returned by malloc().
Try it yourself
#include <stdio.h>
#include <stdlib.h>
int main() {
int count;
// Read the number of integers to store
scanf("%d", &count);
// TODO: Write your code below
// 1. Allocate memory using malloc() with sizeof()
// 2. Check if allocation was successful
// 3. Read the integer values and store them
// 4. Calculate sum and find maximum
// 5. Free the allocated memory
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions6Memory Management
Stack vs. Heap MemoryDynamic Allocation - malloc()Using sizeof() for AllocationChecking Allocation FailureFreeing Memory with free()Allocating with calloc()Recap: Dynamic Array