Dynamic Allocation - malloc()
Part of the Logic & Flow section of Coddy's C journey — lesson 32 of 63.
Now you'll learn about malloc(), the primary function for requesting memory from the heap during program execution. The malloc() function stands for "memory allocation" and allows you to dynamically allocate memory when you need it, rather than declaring fixed-size variables at compile time.
The malloc() function takes one argument: the number of bytes you want to allocate. It returns a void pointer to the allocated memory block, or NULL if the allocation fails. Since it returns a void pointer, you must cast it to the appropriate data type.
#include <stdlib.h>
int *ptr = (int*)malloc(sizeof(int)); // Allocate memory for one integer
// ptr now points to a memory location that can hold an integerThe key advantage of
malloc()is flexibility - you can request exactly the amount of memory you need at runtime, and this memory remains available until you explicitly free it. This is particularly useful when you don't know how much memory you'll need until your program is running.
Remember to include <stdlib.h> to use malloc(), and always cast the returned void pointer to match the data type you're working with.
Challenge
EasyWrite a C program that demonstrates dynamic memory allocation using malloc() to create and work with a single integer on the heap. Your program should:
- Use
malloc()to dynamically allocate memory for one integer - Cast the returned void pointer to an integer pointer
- Read an integer value from the user input
- Store the input value in the dynamically allocated memory using the dereference operator
- Print the stored value in the format:
Stored value: [value] - Calculate and store the square of the value in the same memory location
- Print the squared value in the format:
Squared value: [value]
Remember to include the <stdlib.h> header to use malloc(). Your program should demonstrate the basic workflow of dynamic memory allocation: requesting memory from the heap, using it to store and manipulate data, and working with the allocated memory through pointer operations.
For example, if the user enters 7, your output should be:
Stored value: 7
Squared value: 49This challenge introduces you to the fundamental concept of dynamic memory allocation, where memory is requested at runtime rather than being fixed at compile time, giving your programs greater flexibility in memory usage.
Cheat sheet
The malloc() function allocates memory dynamically from the heap during program execution. It takes the number of bytes to allocate and returns a void pointer to the allocated memory block, or NULL if allocation fails.
Include <stdlib.h> to use malloc():
#include <stdlib.h>
int *ptr = (int*)malloc(sizeof(int)); // Allocate memory for one integerKey points:
- Always cast the returned void pointer to the appropriate data type
- Memory remains available until explicitly freed
- Provides flexibility to request exact memory amounts at runtime
- Use
sizeof()to determine the correct number of bytes needed
Try it yourself
#include <stdio.h>
#include <stdlib.h>
int main() {
// Read input
int input_value;
scanf("%d", &input_value);
// TODO: Write your code below
// 1. Use malloc() to allocate memory for one integer
// 2. Cast the returned pointer to int*
// 3. Store the input value in the allocated memory
// 4. Print the stored value
// 5. Calculate and store the square in the same location
// 6. Print the squared value
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