Launch your tech mastery with us—your coding journey starts now!
Course Content
Basic Syntax and Data Types
0/2
Arrays and Strings
0/2
Structures in C
0/1
Dynamic Memory Management
0/1
Command Line Arguments
0/1
Preprocessor Directives
0/1
C Programming

Dynamic Memory Allocation in C

Definition:
Dynamic memory allocation allows memory to be allocated during runtime using pointers.

🔹 Functions used (in stdlib.h):

Function

Description

malloc()

Allocates memory block

calloc()

Allocates memory and initializes it to 0

realloc()

Re-allocates memory block

free()

Frees allocated memory

Example – Using malloc():

#include <stdio.h>

#include <stdlib.h>

int main() {

    int *ptr;

    ptr = (int *)malloc(3 * sizeof(int));

    if (ptr == NULL) {

        printf(“Memory not allocated\n”);

        return 1;

    }

    ptr[0] = 10;

    ptr[1] = 20;

    ptr[2] = 30;

    for (int i = 0; i < 3; i++) {

        printf(“%d “, ptr[i]);

    }

    free(ptr); // release memory

    return 0;

}