📘 Lesson  ·  Lesson 57

Dynamic Memory (malloc/free)

Dynamic Memory (malloc/free)

What is Dynamic Memory?

💡 Note

Dynamic memory is memory allocated at run-time from the heap using malloc/calloc, resized with realloc, and released with free.

The Functions

FunctionUse
malloc(n)allocate n bytes (uninitialized)
calloc(n,size)allocate and set to zero
realloc(p,n)resize an existing block
free(p)release the memory

Example

C
#include <stdio.h>
#include <stdlib.h>
int main() {
    int *arr = (int*) malloc(3 * sizeof(int));
    arr[0]=10; arr[1]=20; arr[2]=30;
    printf("%d\n", arr[1]);   // 20
    free(arr);                 // always free!
    return 0;
}
Output:
20

Summary

  • malloc/calloc allocate heap memory; realloc resizes; free releases it.
  • Always free to avoid memory leaks.

Dynamic Memory क्या है?

💡 Note

Dynamic memory run-time पर heap से malloc/calloc से allocate होती है, realloc से resize, और free से release।

Functions

FunctionUse
malloc(n)n bytes allocate (uninitialized)
calloc(n,size)allocate और zero set
realloc(p,n)मौजूदा block resize
free(p)memory release

Example

C
#include <stdio.h>
#include <stdlib.h>
int main() {
    int *arr = (int*) malloc(3 * sizeof(int));
    arr[0]=10; arr[1]=20; arr[2]=30;
    printf("%d\n", arr[1]);   // 20
    free(arr);                 // हमेशा free करें!
    return 0;
}
Output:
20

सारांश

  • malloc/calloc heap memory allocate; realloc resize; free release करता है।
  • Memory leaks से बचने को हमेशा free करें।
← Back to C Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n