Dynamic Memory Allocation in C using malloc
Defined the topics: 1. Malloc 2.Calloc 3.Realloc
Every team will make report on the given topics in details and submit here. As this is a teamwork, group members will work on one report. 1. Function of malloc(), calloc(),realloc() 2. Syntax of these 3 methods (With Explanation) 3. Apply these methods in code and explain. 4.Advantage, Disadvantage.
Answer:
1. Functions of malloc(), calloc(), and realloc() malloc(): Allocates a specified amount of memory during runtime and returns a pointer to the first byte of the allocated memory. The memory is uninitialized. calloc(): Allocates memory for an array of elements, initializes all bytes to zero, and returns a pointer to the allocated memory. realloc(): Changes the size of previously allocated memory block. It can be used to increase or decrease the size of the memory allocated and may move the memory to a new location if necessary.
2. Syntax of These Methods malloc(size_t size) Description: Allocates size bytes of memory. Return Value: Returns a pointer to the allocated memory or NULL if the allocation fails. calloc(size_t num, size_t size) Description: Allocates memory for an array of num elements, each of size bytes. Return Value: Returns a pointer to the allocated memory or NULL if the allocation fails. realloc(void *ptr, size_t size) Description: Resizes the memory block pointed to by ptr to size bytes. If ptr is NULL, it behaves like malloc. Return Value: Returns a pointer to the newly allocated memory or NULL if the allocation fails. The original memory block is freed if the allocation fails.
3. Apply These Methods in Code #include <stdio.h> #include <stdlib.h> int main() { int *arr1; arr1 = (int*)malloc(5 * sizeof(int)); if (arr1 == NULL) { printf(“Memory allocation failed\n”); return 1; } int *arr2; arr2 = (int*)calloc(5, sizeof(int)); if (arr2 == NULL) { printf(“Memory allocation failed\n”); free(arr1); return 1; } arr1 = (int*)realloc(arr1, 10 * sizeof(int)); // Resize to hold 10 integers if (arr1 == NULL) { printf(“Reallocation failed\n”); free(arr2); return 1; } free(arr1); free(arr2); return 0; }
4. Advantages and Disadvantages malloc() Advantages: Simple to use; allocates a specific amount of memory. Disadvantages: Memory is uninitialized, which can lead to unpredictable behavior if accessed before initialization. calloc() Advantages: Initializes allocated memory to zero, which can prevent issues with uninitialized data. Disadvantages: Slightly slower than malloc() due to initialization. realloc() Advantages: Allows dynamic resizing of memory, which can be more memory-efficient. Disadvantages: May involve moving memory to a new location, which requires additional overhead; can lead to memory leaks if not handled properly.

