Dynamic Memory Allocation & Pointers
Understanding pointers and memory allocation in C
Introduction to Pointers
A pointer is a variable that stores the memory address of another variable.
Why use pointers?
- Efficient memory management
- Direct access to memory
- Used in data structures like linked lists
Memory Allocation Types
1. Static Allocation:
- Memory is allocated at compile time
- Fixed size, cannot be changed during execution
2. Dynamic Allocation:
- Memory is allocated at runtime
- Flexible, can allocate and deallocate memory as needed
Dynamic Memory Allocation
Functions used for dynamic memory allocation in C:
- malloc(size): Allocates memory of given size
- calloc(n, size): Allocates memory for an array of n elements
- realloc(ptr, new_size): Resizes previously allocated memory
- free(ptr): Deallocates memory to avoid memory leaks
Example Code
Example: Allocating memory using malloc
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int*) malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
return 1;
printf("Memory allocated successfully.\n");
free(ptr);
return 0;
}
Conclusion
- Pointers store addresses and help in efficient memory management.
- Dynamic memory allocation allows flexible use of memory.
- Functions like malloc, calloc, realloc, and free help manage memory.
- Proper memory management is crucial to avoid memory leaks.