0
0
Cprogramming~5 mins

Memory allocation flow

Choose your learning style9 modes available
Introduction

Memory allocation flow shows how a program asks for and uses memory while running. It helps manage space for data and variables.

When you need to store data that changes size during the program.
When you want to create variables or arrays while the program runs.
When you want to use memory efficiently and free it when done.
When working with dynamic data like user input or files.
When building data structures like linked lists or trees.
Syntax
C
void* malloc(size_t size);
void free(void* ptr);

malloc asks the system for a block of memory of the given size in bytes.

free releases the memory back to the system when you no longer need it.

Examples
Allocate memory for one integer and store its address in ptr.
C
int* ptr = (int*) malloc(sizeof(int));
Allocate memory for 100 characters (like a string buffer).
C
char* buffer = (char*) malloc(100 * sizeof(char));
Release the memory previously allocated to ptr.
C
free(ptr);
Sample Program

This program allocates memory for 5 integers, stores values, prints them, and then frees the memory.

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

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

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

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

    free(numbers);
    return 0;
}
OutputSuccess
Important Notes

Always check if malloc returns NULL to avoid errors.

Forgetting to free memory causes memory leaks, which waste system resources.

Memory allocated by malloc is not initialized; it may contain garbage values.

Summary

Memory allocation flow manages how programs get and release memory.

malloc allocates memory; free releases it.

Always check allocation success and free memory when done.