0
0
CHow-ToBeginner · 3 min read

How to Use malloc in C: Simple Guide with Examples

In C, use malloc to allocate memory dynamically by specifying the number of bytes you need. It returns a pointer to the allocated memory, or NULL if allocation fails. Remember to free the memory when done to avoid leaks.
📐

Syntax

The malloc function allocates a block of memory of a specified size in bytes and returns a pointer to the beginning of this block. If it fails, it returns NULL.

  • size_t size: Number of bytes to allocate.
  • void*: Generic pointer to the allocated memory.

You usually cast the returned pointer to the desired type.

c
void *malloc(size_t size);
💻

Example

This example shows how to allocate memory for an array of 5 integers, assign values, print them, and then free the memory.

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

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
    }

    for (int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, arr[i]);
    }

    free(arr);
    return 0;
}
Output
arr[0] = 0 arr[1] = 10 arr[2] = 20 arr[3] = 30 arr[4] = 40
⚠️

Common Pitfalls

Common mistakes when using malloc include:

  • Not checking if malloc returned NULL, which means allocation failed.
  • Forgetting to free allocated memory, causing memory leaks.
  • Using the allocated memory without casting the pointer or with wrong size calculations.
  • Accessing memory out of allocated bounds.
c
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Wrong: Not checking malloc result
    int *ptr = (int *)malloc(3 * sizeof(int));
    // Using ptr without check can cause crash if malloc fails

    // Right: Check malloc result
    if (ptr == NULL) {
        printf("Allocation failed\n");
        return 1;
    }

    // Use memory safely
    for (int i = 0; i < 3; i++) {
        ptr[i] = i + 1;
    }

    for (int i = 0; i < 3; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    free(ptr);
    return 0;
}
Output
1 2 3
📊

Quick Reference

  • malloc(size): Allocates size bytes and returns a pointer.
  • free(ptr): Frees memory previously allocated by malloc.
  • Always check if malloc returns NULL.
  • Cast the returned pointer to the correct type.
  • Use sizeof(type) to calculate the size for allocation.

Key Takeaways

Use malloc to allocate memory dynamically by specifying the number of bytes needed.
Always check if malloc returns NULL to handle allocation failure safely.
Cast the returned void pointer to the correct type before use.
Remember to free allocated memory with free to avoid memory leaks.
Use sizeof to calculate the correct size for the data type you want to allocate.