0
0
Cprogramming~5 mins

malloc function

Choose your learning style9 modes available
Introduction

The malloc function helps you get memory space while your program is running. It lets you ask for memory when you need it, instead of before the program starts.

When you don't know how many items you will need to store before the program runs.
When you want to create a flexible list or array that can grow or shrink.
When you want to save memory by only using what you need at the moment.
When you want to manage memory yourself for better control.
When you want to create complex data structures like linked lists or trees.
Syntax
C
void *malloc(size_t size);

malloc returns a pointer to a block of memory of the requested size in bytes.

If malloc fails to allocate memory, it returns NULL.

Examples
This asks for memory enough to store one integer and saves the address in ptr.
C
int *ptr = (int *)malloc(sizeof(int));
This allocates memory for 100 characters and stores the pointer in buffer. Casting is optional in C.
C
char *buffer = malloc(100 * sizeof(char));
This reserves space for 10 floats in memory.
C
float *arr = malloc(10 * sizeof(float));
Sample Program

This program uses malloc to create an array of 5 integers. It fills the array with multiples of 10, prints them, and then frees the memory.

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

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

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

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

    free(arr); // Always free memory when done
    return 0;
}
OutputSuccess
Important Notes

Always check if malloc returns NULL to avoid using invalid memory.

Remember to use free to release memory when you no longer need it, or your program may waste memory.

malloc does not initialize the memory; it may contain garbage values.

Summary

malloc lets you get memory while your program runs.

You must ask for the right size in bytes and check if it worked.

Always free the memory after use to keep your program healthy.