C malloc() Function | Allocate Dynamic Memory

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

Introduction

The malloc() function in C is a standard library function that allocates a block of memory of a specified size. It is part of the C standard library (stdlib.h). This function is commonly used for dynamic memory allocation, allowing programs to request memory at runtime.

malloc() Function Syntax

The syntax for the malloc() function is as follows:

void *malloc(size_t size);

Parameters:

  • size: The number of bytes to allocate.

Returns:

  • The function returns a pointer to the allocated memory. If the allocation fails, it returns NULL.

Understanding malloc() Function

The malloc() function allocates a contiguous block of memory of the specified size and returns a pointer to the beginning of this block. The contents of the allocated memory are not initialized and may contain garbage values. It is important to check the returned pointer to ensure that the memory allocation was successful before using the allocated memory.

Examples

Allocating a Single Memory Block

To demonstrate how to use malloc() to allocate a single memory block, we will write a simple program.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;

    // Allocate memory for an integer
    ptr = (int *)malloc(sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    // Use the allocated memory
    *ptr = 42;
    printf("Allocated integer value: %d\n", *ptr);

    // Free the allocated memory
    free(ptr);

    return 0;
}

Output:

Allocated integer value: 42

Allocating an Array

This example shows how to use malloc() to allocate memory for an array of integers.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array;
    int num_elements = 5;
    int i;

    // Allocate memory for an array of integers
    array = (int *)malloc(num_elements * sizeof(int));
    if (array == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    // Initialize and print the array
    for (i = 0; i < num_elements; i++) {
        array[i] = i * 2;
        printf("array[%d] = %d\n", i, array[i]);
    }

    // Free the allocated memory
    free(array);

    return 0;
}

Output:

array[0] = 0
array[1] = 2
array[2] = 4
array[3] = 6
array[4] = 8

Real-World Use Case

Dynamic Memory Allocation for Data Structures

In real-world applications, dynamic data structures such as linked lists, trees, and graphs often require dynamic memory allocation. The malloc() function is used to allocate memory for new elements as needed.

Example: Allocating Memory for a Linked List Node

#include <stdio.h>
#include <stdlib.h>

// Define a node structure
struct Node {
    int data;
    struct Node *next;
};

int main() {
    // Allocate memory for a new node
    struct Node *node = (struct Node *)malloc(sizeof(struct Node));
    if (node == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    // Initialize the node
    node->data = 10;
    node->next = NULL;

    // Print the node's data
    printf("Node data: %d\n", node->data);

    // Free the allocated memory
    free(node);

    return 0;
}

Output:

Node data: 10

Conclusion

The malloc() function is used for dynamic memory allocation in C. By understanding and using this function correctly, you can allocate memory at runtime, enabling the implementation of dynamic data structures and efficient memory management in your programs. 

Always ensure to check for successful memory allocation and to free the allocated memory when it is no longer needed to prevent memory leaks.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare