SlideShare a Scribd company logo
Memory Management
System Programing BSCS
Introduction
• Since C is a structured language, it has some fixed rules for
programming. One of them includes changing the size of an
array. An array is a collection of items stored at contiguous
memory locations.
Dynamic Memory Allocation in C
• If there is a situation where only 5 elements are needed to be
entered in this array. In this case, the remaining 4 indices are
just wasting memory in this array. So there is a requirement to
lessen the length (size) of the array from 9 to 5.
• Take another situation. In this, there is an array of 9 elements
with all 9 indices filled. But there is a need to enter 3 more
elements in this array. In this case, 3 indices more are required.
So the length (size) of the array needs to be changed from 9 to
12.
Dynamic Memory Allocation in C
• Dynamic Memory Allocation is a way through which the size of
data structure can be changed during execution (on run time).
• Memory assigned to a program in a typical architecture can be
divided into four segments.
• Code
• Static/ Global Variables.
• Stack
• heap
The Process’s Memory
• Each process has its own virtual address space dynamically translated into
physical memory address space by the MMU (and the kernel.)
• This space is divided in several part,
• A stack where local and volatile data are stored,
• Global variables and an unorganized space for program’s data called the heap.
• The heap is a continuous (in term of virtual addresses) space of memory
with three bounds:
• a starting point
• a maximum limit (managed through sys/ressource.h’s functions getrlimit(2) and
setrlimit(2))
• End point called the break.
• The break marks the end of the mapped memory space, that is, the part of
the virtual address space that has correspondence into real memory.
Family of stdlib.h
• Dynamic memory allocation could be achieved by using four
functions:
• malloc()
• calloc()
• free()
• realloc()
malloc
• Malloc( ) stands for memory allocation
• It reserves a block of memory with the given amount of bytes.
• The return value is a void pointer to the allocated space
• Therefore the void pointer needs to be casted to appropriate type as
per the requirement.
• However, if the space is insufficient, allocation of memory fails and
returns a NULL pointer.
• All the values at allocated memory are initialized to garbage values
Syntax of malloc
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
• Since the size of int is 4 bytes, this statement will allocate 400
bytes of memory. And, the pointer ptr holds the address of the
first byte in the allocated memory.
• If space is insufficient, allocation fails and returns a NULL
pointer.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %dn", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); }
else {
printf("Memory successfully allocated using malloc.n");
for (i = 0; i < n; ++i) { ptr[i] = i + 1; }
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); }
} return 0;
}
brk(2) and sbrk(2)
• brk(2) place the break at the given address addr and return 0 if
successful, -1 otherwise. The global errno symbol indicate the nature
of the error.
int brk(const void *addr );
• sbrk(2) move the break by the given increment (in bytes.) Depending
on system implementation, it returns the previous or the new break
address. On failure, it returns (void *)-1 and set errno.
void* sbrk(intptr_t incr );
• On some system sbrk accepts negative values (in order to free some
mapped memory.)
The Process’s Memory..
In order to code a malloc, we need to know where the heap begin and the
break position, and of course we need to be able to move the break. This the
purpose of the two syscalls brk and sbrk.
Calloc()
• Calloc() stands for Contiguous allocation
• It reserves n blocks of memory with the given amount of bytes
• The return value is a void pointer to the allocated space
• Therefore the void pointer needs to be casted to the appropriate type
as per the requirments
• However, if the space is sufficient, allocation of memory fails and it
return a null pointer.
• All the values at allocated memory are initialized to 0
• Systanx:
• Prt = (ptr-type*) calloc (n, size_in_bytes)
Realloc()
• realloc() stands for reallocation
• If the dynamically allocated memory is insufficient we can change the
size of the pervious allocated memory using realloc () function
• Syntax:
• Ptr = (ptr-type*) realloc (ptr, new_size_in_bytes)
Free()
• Free() is used to free the allocated memory
• If the dynamically allocated memory is not required anymore, we can
free it using free function
• This will free the memory being used by the program in the heap
• Syntax:
• free(ptr)
Difference between malloc() and calloc()
S.No. malloc() calloc()
1. malloc() function creates a single
block of memory of a specific size.
calloc() function assigns multiple blocks of
memory to a single variable.
2. The number of arguments in malloc()
is 1.
The number of arguments in calloc() is 2.
3. malloc() is faster. calloc() is slower.
4. malloc() has high time efficiency. calloc() has low time efficiency.
5. The memory block allocated by
malloc() has a garbage value.
The memory block allocated by calloc() is
initialized by zero.
6. malloc() indicates memory allocation. calloc() indicates contiguous allocation.

More Related Content

PPTX
Dynamic Memory Allocation in C
PPTX
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
PPTX
Dynamic Memory allocation
PDF
dynamic-allocation.pdf
PPTX
final GROUP 4.pptx
PPTX
C dynamic ppt
DOCX
Dma
Dynamic Memory Allocation in C
Lecture 3.3.1 Dynamic Memory Allocation and Functions.pptx
Dynamic Memory allocation
dynamic-allocation.pdf
final GROUP 4.pptx
C dynamic ppt
Dma

Similar to Memory Management.pptx (20)

PPTX
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
PDF
Dynamic memory allocation
PPTX
dynamic_v1-3.pptx
PPT
CLanguage_ClassPPT_3110003_unit 9Material.ppt
PPTX
DYNAMIC MEMORY ALLOCATION.pptx
PPTX
DYNAMIC MEMORY ALLOCATION.pptx
PPTX
Dynamic memory allocation
PPTX
Structures_and_Files[1] - Read-Only.pptx
DOCX
DS UNIT3_LINKED LISTS.docx
PPTX
Dynamic memory allocation
PPT
Bullet pts Dyn Mem Alloc.pptghftfhtfytftyft
PPTX
Dynamic memory allocation
PPTX
PPTX
Stack & heap
PPT
Dynamic Memory Allocation
PPSX
4 dynamic memory allocation
PPTX
Dynamic memory allocation
PPTX
Dynamic memory Allocation in c language
PPTX
Dynamic Memory Allocation.pptx
PPTX
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
Unit-9zxknaksldmoasdoiasmdmiojoisa(DMA).pptx
Dynamic memory allocation
dynamic_v1-3.pptx
CLanguage_ClassPPT_3110003_unit 9Material.ppt
DYNAMIC MEMORY ALLOCATION.pptx
DYNAMIC MEMORY ALLOCATION.pptx
Dynamic memory allocation
Structures_and_Files[1] - Read-Only.pptx
DS UNIT3_LINKED LISTS.docx
Dynamic memory allocation
Bullet pts Dyn Mem Alloc.pptghftfhtfytftyft
Dynamic memory allocation
Stack & heap
Dynamic Memory Allocation
4 dynamic memory allocation
Dynamic memory allocation
Dynamic memory Allocation in c language
Dynamic Memory Allocation.pptx
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
Ad

Recently uploaded (20)

PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
Safety Seminar civil to be ensured for safe working.
PPT
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
PDF
Visual Aids for Exploratory Data Analysis.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PDF
Analyzing Impact of Pakistan Economic Corridor on Import and Export in Pakist...
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
UNIT 4 Total Quality Management .pptx
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PDF
Abrasive, erosive and cavitation wear.pdf
PPTX
Current and future trends in Computer Vision.pptx
PPTX
introduction to high performance computing
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Safety Seminar civil to be ensured for safe working.
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
Visual Aids for Exploratory Data Analysis.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Analyzing Impact of Pakistan Economic Corridor on Import and Export in Pakist...
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Fundamentals of Mechanical Engineering.pptx
Categorization of Factors Affecting Classification Algorithms Selection
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Fundamentals of safety and accident prevention -final (1).pptx
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
UNIT 4 Total Quality Management .pptx
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
Abrasive, erosive and cavitation wear.pdf
Current and future trends in Computer Vision.pptx
introduction to high performance computing
Ad

Memory Management.pptx

  • 2. Introduction • Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.
  • 3. Dynamic Memory Allocation in C • If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5. • Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.
  • 4. Dynamic Memory Allocation in C • Dynamic Memory Allocation is a way through which the size of data structure can be changed during execution (on run time). • Memory assigned to a program in a typical architecture can be divided into four segments. • Code • Static/ Global Variables. • Stack • heap
  • 5. The Process’s Memory • Each process has its own virtual address space dynamically translated into physical memory address space by the MMU (and the kernel.) • This space is divided in several part, • A stack where local and volatile data are stored, • Global variables and an unorganized space for program’s data called the heap. • The heap is a continuous (in term of virtual addresses) space of memory with three bounds: • a starting point • a maximum limit (managed through sys/ressource.h’s functions getrlimit(2) and setrlimit(2)) • End point called the break. • The break marks the end of the mapped memory space, that is, the part of the virtual address space that has correspondence into real memory.
  • 6. Family of stdlib.h • Dynamic memory allocation could be achieved by using four functions: • malloc() • calloc() • free() • realloc()
  • 7. malloc • Malloc( ) stands for memory allocation • It reserves a block of memory with the given amount of bytes. • The return value is a void pointer to the allocated space • Therefore the void pointer needs to be casted to appropriate type as per the requirement. • However, if the space is insufficient, allocation of memory fails and returns a NULL pointer. • All the values at allocated memory are initialized to garbage values
  • 8. Syntax of malloc ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); • Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. • If space is insufficient, allocation fails and returns a NULL pointer.
  • 9. #include <stdio.h> #include <stdlib.h> int main() { int* ptr; int n, i; printf("Enter number of elements:"); scanf("%d",&n); printf("Entered number of elements: %dn", n); ptr = (int*)malloc(n * sizeof(int)); if (ptr == NULL) { printf("Memory not allocated.n"); exit(0); } else { printf("Memory successfully allocated using malloc.n"); for (i = 0; i < n; ++i) { ptr[i] = i + 1; } printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } return 0; }
  • 10. brk(2) and sbrk(2) • brk(2) place the break at the given address addr and return 0 if successful, -1 otherwise. The global errno symbol indicate the nature of the error. int brk(const void *addr ); • sbrk(2) move the break by the given increment (in bytes.) Depending on system implementation, it returns the previous or the new break address. On failure, it returns (void *)-1 and set errno. void* sbrk(intptr_t incr ); • On some system sbrk accepts negative values (in order to free some mapped memory.)
  • 11. The Process’s Memory.. In order to code a malloc, we need to know where the heap begin and the break position, and of course we need to be able to move the break. This the purpose of the two syscalls brk and sbrk.
  • 12. Calloc() • Calloc() stands for Contiguous allocation • It reserves n blocks of memory with the given amount of bytes • The return value is a void pointer to the allocated space • Therefore the void pointer needs to be casted to the appropriate type as per the requirments • However, if the space is sufficient, allocation of memory fails and it return a null pointer. • All the values at allocated memory are initialized to 0 • Systanx: • Prt = (ptr-type*) calloc (n, size_in_bytes)
  • 13. Realloc() • realloc() stands for reallocation • If the dynamically allocated memory is insufficient we can change the size of the pervious allocated memory using realloc () function • Syntax: • Ptr = (ptr-type*) realloc (ptr, new_size_in_bytes)
  • 14. Free() • Free() is used to free the allocated memory • If the dynamically allocated memory is not required anymore, we can free it using free function • This will free the memory being used by the program in the heap • Syntax: • free(ptr)
  • 15. Difference between malloc() and calloc() S.No. malloc() calloc() 1. malloc() function creates a single block of memory of a specific size. calloc() function assigns multiple blocks of memory to a single variable. 2. The number of arguments in malloc() is 1. The number of arguments in calloc() is 2. 3. malloc() is faster. calloc() is slower. 4. malloc() has high time efficiency. calloc() has low time efficiency. 5. The memory block allocated by malloc() has a garbage value. The memory block allocated by calloc() is initialized by zero. 6. malloc() indicates memory allocation. calloc() indicates contiguous allocation.