Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

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:

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

Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples

Key Takeaways

malloc() works with any data type—including characters, structures, and user-defined types—providing flexible memory management for C programmers.

C Language

  1. C++ Structs Explained with a Practical Example
  2. Mastering C++ Vectors: Dynamic Arrays, Iterators, and Practical Examples
  3. Mastering std::map in C++: Comprehensive Guide with Code Examples
  4. C++ Polymorphism Explained: Practical Examples & Key Concepts
  5. Mastering std::list in C++: Syntax, Functions & Practical Examples
  6. C# Enumerations (Enums) – Definition, Example, and Usage
  7. calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example
  8. Using realloc() in C: Syntax, Best Practices & Example
  9. Mastering C’s free() Function: Practical Guide & Example
  10. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples