Apply for Zend Framework Certification Training

c




< Create an code for palendrome Last >



13  Dynamic Memory Allocation in C ,malloc(), calloc(), realloc(), free()
Dynamic Memory Allocation (DMA) in C means allocating memory at runtime (during program execution) instead of compile time.
Dynamic memory allocation allows a program to request memory from the heap using functions like:
malloc()
calloc()
realloc()
free()
1)Allocating memory at runtime means:
Memory is given to your program while it is running, not before it starts.
Simple Explanation
Compile time = Before program runs
Runtime = When program is actually executing
So, runtime allocation =
 “Program asks for memory when it needs it during execution.”
 
Example (Real-Life)
Imagine:
You go to a hotel
You don’t book a room in advance
You request a room when you arrive
That is runtime allocation
(You take memory only when needed)
 
Runtime vs Compile Time
Feature Compile Time Allocation Runtime Allocation
When Before execution During execution
Example int arr[10]; malloc()
Flexibility Fixed size Variable size
 
3)What is Heap Memory?
In simple terms, Heap is a region of a computer’s memory used for dynamic memory allocation—that means memory is allocated at runtime (during program execution) instead of compile time.
Heap = A large pool of memory where you can request and release memory manually when needed
 
 
These functions are available in the <stdlib.h> header file.
What is malloc() in C?
malloc() (Memory Allocation) is a function from the stdlib.h library used to dynamically allocate memory at runtime.
malloc() allocates a block of memory of a specified size (in bytes) and returns a pointer to the first byte of that memory.
 
Why use Dynamic Memory Allocation?
When the size of data is not known in advance
To use memory efficiently
To create flexible data structures (like arrays, linked lists, etc.)
Example of malloc
#include <stdio.h>
#include <stdlib.h>
int main() {
    int *ptr;
    int n;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    // Dynamic memory allocation
    ptr = (int*) malloc(n * sizeof(int));
    // Input
    for(int i = 0; i < n; i++) {
        scanf("%d", &ptr[i]);
    }
    // Output
    for(int i = 0; i < n; i++) {
        printf("%d ", ptr[i]);
    }
    // Free memory
    free(ptr);
    return 0;
}
 
Static vs Dynamic Memory
Static Memory Dynamic Memory
Allocated at compile time Allocated at runtime
Fixed size Flexible size
Uses stack Uses heap
LIFO    Garbage collectore
Purpose of free() in C
The free() function is used to release dynamically allocated memory back to the system (heap).
free() deallocates the memory that was previously allocated using:
malloc()
calloc()
realloc()
Syntax
free(pointer);
Why is free() important?
Prevents memory leaks
Makes memory available for reuse
Improves program efficiency
Avoids unnecessary memory consumption
Example of free()
#include <stdio.h>
#include <stdlib.h>
int main() {
   int *ptr = (int*) malloc(5 * sizeof(int));
   printf("Memory allocation %d",*ptr);
   free(ptr);
   printf("Memory allocation %d",*ptr);
   return 0;
}
 
Q1)Write a C program that:
Takes the number of students in a class as input from the user.
Dynamically allocates memory to store the marks of all students using malloc().
Accepts the marks of each student from the user.
Displays the marks of all students.
Frees the allocated memory after use.
Solution
#include <stdio.h>
#include <stdlib.h>
int main(){
    int *arr;
    int n,i;
    printf("Enter the number of students in a class ");
    scanf("%d",&n);
    arr = (int*) malloc(n*sizeof(i));
    for(i=0;i<n;i++){
        printf("Enter the marks of the student %d ",i+1);
        scanf("%d",&arr[i]);
    }
    printf("The marks of the students are ");
    for(i=0;i<n;i++){
        printf(" %d ",arr[i]);
    }
    free(arr);
    return 0;
}
 
Using calloc() (Zero-initialized memory)
Difference from malloc():
malloc() → gives garbage values
calloc() → gives all values initialized to 0
Program using calloc()
#include <stdio.h>
#include <stdlib.h>
int main(){
    int *arr;
    int n, i;
    printf("Enter number of students: ");
    scanf("%d", &n);
    arr = (int*) calloc(n, sizeof(int));
    for(i = 0; i < n; i++){
        printf("Enter marks of student %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    printf("\nMarks of students:\n");
    for(i = 0; i < n; i++){
        printf("%d ", arr[i]);
    }
    free(arr);
    return 0;
}
 
Using realloc() (Resize memory)
Used when you want to increase/decrease memory size dynamically
Program using realloc()
#include <stdio.h>
#include <stdlib.h>
int main(){
    int *arr;
    int n, new_n, i;
    printf("Enter initial number of students: ");
    scanf("%d", &n);
    arr = (int*) malloc(n * sizeof(int));
    for(i = 0; i < n; i++){
        printf("Enter marks of student %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    printf("\nEnter new number of students: ");
    scanf("%d", &new_n);
    arr = (int*) realloc(arr, new_n * sizeof(int));
    // Input for new students
    for(i = n; i < new_n; i++){
        printf("Enter marks of student %d: ", i + 1);
        scanf("%d", &arr[i]);
    }
    printf("\nUpdated marks:\n");
    for(i = 0; i < new_n; i++){
        printf("%d ", arr[i]);
    }
    free(arr);
    return 0;
}

< Create an code for palendrome Last >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top