Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples
What Is malloc() in C?
In the C Standard Library, malloc()—short for “memory allocation”—dynamically reserves a contiguous block of memory at runtime. The function returns a void* pointer to the beginning of that block, which you can cast to any pointer type you need.
Syntax
ptr = (cast_type *)malloc(byte_size);
Where:
ptris a pointer of the specifiedcast_type.byte_sizeis the number of bytes to allocate.
Example:
ptr = (int *)malloc(50);
After this call, 50 bytes of memory are reserved, and ptr points to the first byte of that space.
Practical Example
#include <stdlib.h>
#include <stdio.h>
int main() {
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* Allocate space for 15 integers */
if (ptr != NULL) {
*(ptr + 5) = 480; /* Assign 480 to the sixth integer */
printf("Value of the 6th integer is %d", *(ptr + 5));
}
return 0;
}
Output:
Value of the 6th integer is 480

Key Takeaways
- Using
sizeof(*ptr)instead ofsizeof(int)makes the code resilient to later changes in the pointer’s type. - If the system cannot satisfy the request,
malloc()returnsNULL; always check for a null pointer before using the memory. - The allocated block is contiguous and can be treated as an array. Pointer arithmetic is preferred over the subscript operator to avoid modifying the original pointer value.
malloc() works with any data type—including characters, structures, and user-defined types—providing flexible memory management for C programmers.
C Language
- C++ Structs Explained with a Practical Example
- Mastering C++ Vectors: Dynamic Arrays, Iterators, and Practical Examples
- Mastering std::map in C++: Comprehensive Guide with Code Examples
- C++ Polymorphism Explained: Practical Examples & Key Concepts
- Mastering std::list in C++: Syntax, Functions & Practical Examples
- C# Enumerations (Enums) – Definition, Example, and Usage
- calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example
- Using realloc() in C: Syntax, Best Practices & Example
- Mastering C’s free() Function: Practical Guide & Example
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples