Dynamic Memory in C
0 329
Dynamic memory allocation assists you to allocate memory during runtime.
It enables adaptable memory handling for your program.
static memory occurs at compile time.
Dynamic memory allows you to allocate memory while your program is running.
This ability improves the versatility, allowing for effective memory management according to the program's needs.
Dynamic memory allocation in C involves using functions like malloc, calloc, realloc, and free.
Malloc
Malloc is the short form of memory allocation in C.
Its function is to allocate a certain amount of memory in bytes.
If you specify how many bytes of memory you need malloc tries to provide you with that much memory.
If there is no memory available it returns a Null.
Syntax of Malloc in C
void* malloc(size_t size);
Calloc
Calloc is the short form of contiguous memory allocation in C.
Its function is used for allocating memory space for the array of elements.
If you specify how many elements you need in the array and the size of each element.
Calloc tries to provide you with that much memory.
If there is no memory available it returns Null.
Syntax of Calloc in C
void* calloc(size_t num, size_t size);
Realloc
Realloc is the short form of Re allocation in C.
It's a useful function for changing the size of memory you've already reserved.
If You specify how much bigger or smaller memory size you want.
Realloc then tries to adjust the memory size accordingly.
If it manages to do so, it gives you a pointer to the beginning of the newly resized memory block.
If it can't resize the memory, it returns NULL.
Syntax of Realloc in C
void* realloc(void* ptr, size_t size);
Free
Free function is used to deallocate memory previously allocated by malloc, calloc, realloc.
when you finish using memory space allocated by malloc, calloc, or realloc, you use "free" to release that memory back to the system.
you have to pass the pointer to the memory you want to release to free.
It doesn't provide any result because it is used to release the memory.
Syntax of Free
void free(void* ptr);
Program for Dynamic Memory in C
#include <stdio.h> #include <stdlib.h> int main() { int *p; int A, B, Total = 0; printf("Enter the number of elements: "); scanf("%d",&A); // Dynamically allocate memory for an array of n integers p= (int*) malloc(A * sizeof(int)); if(p == NULL) { printf("Memory allocation failed."); return 1; } // Input elements from the user printf("Enter %d elements:\n", A); for(B = 0; B < A; B++) { scanf("%d", &p[B]); } for(B = 0; B < A; B++) { Total+= p[B]; } printf("Total = %d\n", Total); // Free dynamically allocated memory free(p); return 0; }Output:
Enter the number of elements: 3 Enter 3 elements:4 5 6 Total = 15
Share:
Comments
Waiting for your comments