Dynamic Memory Allocation
Dynamic Memory Allocation
ALLOCATION
• Dynamic memory allocation is a concept in
computer programming that refers to the allocation
and deallocation of memory during the execution of
a program. Unlike static memory allocation, where
memory is allocated at compile-time, dynamic
memory allocation allows the program to request
memory at runtime.
• In many programming languages, dynamic memory allocation is
typically performed using functions or operators specifically designed
for this purpose, such as malloc, calloc, realloc (in C and C++), or the
new operator (in C++). These functions allow you to allocate memory
dynamically and return a pointer to the allocated memory block.
MALLOC:
• #include <stdlib.h>
• void* calloc(size_t num, size_t size);
• The calloc() function takes two arguments: num and size. num specifies
the number of elements to allocate, and size specifies the size of each
element. It returns a void* pointer to the allocated memory block with
all bytes initialized to zero.
• #include <stdio.h>
• #include <stdlib.h>
• int main() {
• int* ptr;
• #include <stdlib.h>
• int main() {
• int* ptr;
• ptr = (int*)malloc(sizeof(int));
• if (ptr == NULL) {
• return 1;
• }
• *ptr = 42;
• free(ptr);
• return 0;
• }