From ebb5870800f211a285133fc6c5b1be6e1dbf44d2 Mon Sep 17 00:00:00 2001 From: Yasaswini Ganji <106906121+yasaswini999@users.noreply.github.com> Date: Wed, 5 Oct 2022 12:25:35 +0530 Subject: [PATCH] Create yasaswini999.md Blog on dynamic memory allocation in C --- blogs/yasaswini999.md | 134 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 blogs/yasaswini999.md diff --git a/blogs/yasaswini999.md b/blogs/yasaswini999.md new file mode 100644 index 0000000..6c96d38 --- /dev/null +++ b/blogs/yasaswini999.md @@ -0,0 +1,134 @@ +## Dynamic Memory Allocation in C + +- In this article, we will discuss how memory can be allocated dynamically in the C programming language. + +### Introduction + +> Memory that has been allocated at compilation time cannot be altered after execution. This will result in a problem with memory loss or inadequacy. +> +> - The answer is to dynamically create memory, that is, according to user requirements as the programme is being run. +>- There are two ways to allocate memory: +> > 1. static Memory Allocation +> > 2. Dynamic Memory Allocation + +The standard library functions used for dynamic memory management are: + + + - Malloc() + - Calloc() + - Realloc() + - Free() + ## Malloc() + - Using this function, a runtime byte-sized memory block can be allocated. + - It gives back a void pointer that points to the base address of the memory that was allocated. + - Unknown values will be present in the allotted RAM because it has not been initialised. + + **Syntax:** +``` +void *malloc (size in bytes); +``` +## Calloc() + - This function is utilized to allocate continuous memory chunks during runtime. +- This was created specifically for arrays. +- It gives back a void pointer that points to the base address of the memory that was allocated. + + +**Syntax:** +``` + void *calloc ( numbers of elements, size in bytes); +``` +## Realloc() + - It can reduce (or) extend the allocated memory and reallocates previously allocated memory. + - It then returns a void pointer that points to the base address of the newly allocated memory. + **Syntax:** +``` +void *realloc (pointer, newsize); +``` +## Free() + - With dynamic runtime allocation, it is our obligation to release the space when it is not needed for efficient memory consumption. + - This function frees (or) dealslocates previously allocated memory space. + **Syntax:** +``` +void *free (pointer); +``` + + +**program to demonstrate standard library functions used for dynamic memory management.** +``` +#include + +void main() + +{ + +int *arr,i,j,n; + +clrscr(); + +printf("enter the number of elements in array"); + +scanf("%d",&n); + +arr=(int*) malloc(n*sizeof(int)); //dynamically allocating memory + +//code to read the elements of an array + +for(i=0;i