Back to C Programming
2026-07-155 min read

C malloc()

Learn C malloc() step by step with clear examples and exercises.

Why This Matters

In this full guide, we'll delve into the powerful tool called malloc() in C programming that allows you to dynamically allocate memory during runtime. This skill is essential for solving real-world problems and acing interviews by demonstrating your ability to manage memory effectively.

Prerequisites

To fully grasp the concepts of dynamic memory allocation using malloc(), it's crucial to have a strong foundation in C programming basics, including:

  1. Data types and variables
  2. Control structures (if-else, loops)
  3. Pointers and arrays
  4. Basic input/output operations

Core Concept

Dynamic memory allocation is the process of requesting and releasing memory during program execution to accommodate data that isn't known at compile time. This flexibility is crucial when dealing with variable-sized data structures like lists, trees, or dynamic arrays.

The malloc() function in C provides a simple way to obtain dynamically allocated memory. It takes the number of bytes required as an argument and returns a pointer to the allocated memory block. Here's the syntax:

void* malloc(size_t size);

Let's break down this function:

  1. void*: The return type is a pointer to a generic void, as the memory returned can contain any data type.
  2. size_t: This is an unsigned integer type that represents the size of the memory block you want to allocate in bytes.
  3. malloc(): The function name itself.

Memory Allocation Example

To illustrate how malloc() works, let's create a simple program that dynamically allocates memory for an array and stores integers in it:

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

int main() {
int *array; // Declare a pointer to an integer array
int size = 5; // Define the desired array size

// Allocate memory for the array using malloc()
array = (int*)malloc(size * sizeof(int));

if (array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initialize the array elements with some values
for (int i = 0; i < size; ++i) {
array[i] = i * i;
}

// Print the contents of the array
printf("Array elements:\n");
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}

// Free the allocated memory using free()
free(array);

return 0;
}

In this example, we first declare a pointer to an integer array. Then, we allocate memory for the array using malloc(), taking into account both the number of elements and their data type (using sizeof(int)). After ensuring that memory allocation was successful, we initialize the array elements with some values and print them out. Finally, we free the allocated memory using the free() function before exiting the program.

Worked Example

Let's extend our previous example by reading integers from user input and storing them in the dynamically allocated array:

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

int main() {
int *array; // Declare a pointer to an integer array
int size = 0; // Initialize array size as 0

printf("Enter the number of elements: ");
scanf("%d", &size);

// Allocate memory for the array using malloc()
array = (int*)malloc(size * sizeof(int));

if (array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Read integers from user input and store them in the array
for (int i = 0; i < size; ++i) {
printf("Enter element %d: ", i + 1);
scanf("%d", &array[i]);
}

// Print the contents of the array
printf("\nArray elements:\n");
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}

// Free the allocated memory using free()
free(array);

return 0;
}

In this example, we first prompt the user to enter the number of elements they want in the array. We then allocate memory for the array based on that input and read integers from user input, storing them in the dynamically allocated array. After printing out the contents of the array, we free the allocated memory using free().

Common Mistakes

  1. Forgetting to include stdlib.h: The malloc() function is declared in this header file, so you must include it to use it.
  2. Not checking for NULL return value: If memory allocation fails, malloc() returns a null pointer. Always check the return value before using the allocated memory.
  3. Leaking memory: Don't forget to free dynamically allocated memory when it's no longer needed to avoid memory leaks.
  4. Incorrect size calculation: Make sure you calculate the size of the memory block correctly, including the data type and any multipliers like array dimensions.
  5. Casting malloc() return value: Although not strictly necessary in C99 and later versions, it's a good practice to cast the malloc() return value to the appropriate data type to avoid potential issues with compiler warnings or errors.

Practice Questions

  1. Write a program that dynamically allocates memory for a 2D array of integers and initializes its elements using a nested loop.
  2. Modify the previous example to handle cases where the user enters an invalid number of elements (e.g., a negative value).
  3. Write a program that uses malloc() to create a dynamically allocated linked list of strings, allowing users to add, delete, and search for specific words.

FAQ

  1. Why do we need dynamic memory allocation in C? Dynamic memory allocation allows us to create data structures with variable sizes at runtime, making our programs more flexible and efficient in handling different input cases.
  2. What happens if we don't free dynamically allocated memory in C? If you don't free dynamically allocated memory, it will be leaked, potentially leading to program crashes or consuming excessive resources.
  3. Is there a limit to the amount of memory we can allocate using malloc() in C? The maximum amount of memory that can be allocated using malloc() depends on the system's available memory and may vary between different operating systems.
  4. What is the difference between calloc(), realloc(), and free() in C?
  • calloc(): Allocates memory for an array of elements, initializing each element to zero.
  • realloc(): Resizes an existing memory block or moves it to a new location and adjusts the pointer accordingly.
  • free(): Frees the memory previously allocated by malloc(), calloc(), or realloc().