Dynamic memory allocation (malloc, calloc, realloc, free).
Lesson 4.4: Dynamic Memory Allocation
In this lesson, you'll learn how to allocate and manage memory dynamically during the execution of your C programs. This is a crucial skill for handling situations where you don't know the exact amount of memory you'll need in advance, such as when dealing with user input or variable-sized data structures.
1. Dynamic vs. Static Memory Allocation
Static Allocation:
Memory is allocated at compile time (before your program runs).
The size of arrays and other data structures is fixed and cannot be changed during execution.
Dynamic Allocation:
Memory is allocated at runtime (while your program is running).
You can request memory as needed and release it when you're done, giving you more flexibility and control.
2. Dynamic Memory Allocation Functions
C provides four essential functions for dynamic memory allocation:
malloc() (memory allocation):
Allocates a block of memory of the specified size in bytes.
Returns a void pointer to the first byte of the allocated memory block.
If the allocation fails (e.g., not enough memory), it returns NULL.
C
int *ptr = (int*)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
calloc() (contiguous allocation):
Similar to malloc(), but it also initializes all bytes of the allocated memory to zero.
Useful for arrays where you want to start with all elements set to zero.
C
int *ptr = (int*)calloc(5, sizeof(int)); // Allocate and zero-initialize memory for 5 integers
realloc() (reallocation):
Resizes a previously allocated memory block.
Can expand or shrink the block as needed.
Returns a pointer to the new memory block (which might be at a different address).
If reallocation fails, it returns NULL.
C
ptr = (int*)realloc(ptr, 10 * sizeof(int)); // Expand to hold 10 integers
free():
Releases (deallocates) a memory block that was previously allocated using malloc(), calloc(), or realloc().
Important for preventing memory leaks (when your program uses up all available memory).
C
free(ptr); // Release the allocated memory
3. Example: Dynamic Array
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int *dynamicArray;
int size;
printf("Enter the number of elements: ");
scanf("%d", &size);
dynamicArray = (int*)malloc(size * sizeof(int));
if (dynamicArray == NULL) {
fprintf(stderr, "Memory allocation failed!\n");
return 1; // Exit with an error code
}
printf("Enter the elements:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &dynamicArray[i]);
}
printf("The elements are:\n");
for (int i = 0; i < size; i++) {
printf("%d ", dynamicArray[i]);
}
free(dynamicArray); // Deallocate the memory
return 0;
}
Key Points to Remember
Include stdlib.h: All the memory allocation functions are defined in this header file.
Casting: You need to cast the return value of malloc(), calloc(), and realloc() to the appropriate pointer type.
Error Handling: Always check if the memory allocation was successful (the returned pointer is not NULL) before using it.
Freeing Memory: Make sure to free() the allocated memory when you no longer need it.
Let me know if you want me to expand on any part of this or provide additional examples.