Back to Browse

#DYNAMIC #MEMORY #ALLOCATION IN C| #CALLOC | #MALLOC | #REALLOC | #FREE|

720 views
Premiered Jan 2, 2023
27:48

Dynamic Memory Allocation in C C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime. C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under "stdlib.h" header file to facilitate dynamic memory allocation in C programming. They are: 1. malloc() 2. calloc() 3. free() 4. realloc() 1. malloc() function The “malloc” or “memory allocation” function in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t initialize memory at execution time so that it has initialized each block with the default garbage value initially. Syntax: ptr = (cast-type POINTER) malloc(byte-size) For Example: ptr = (int POINTER) malloc(100 MULTIPLY 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. 2. calloc() function 1. “calloc” or “contiguous allocation” function in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are: 2. It initializes each block with a default value ‘0’. 3. It has two parameters or arguments as compare to malloc(). Syntax: ptr = (cast-type POINTER)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element. For Example: ptr = (float POINTER) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float. realloc() function “realloc” or “re-allocation” function in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.

Download

0 formats

No download links available.

#DYNAMIC #MEMORY #ALLOCATION IN C| #CALLOC | #MALLOC | #REALLOC | #FREE| | NatokHD