Dynamic memory allocation
Dynamic Memory Allocation Dynamic memory allocation is the process by which a program creates and uses memory during runtime. This differs from static memory...
Dynamic Memory Allocation Dynamic memory allocation is the process by which a program creates and uses memory during runtime. This differs from static memory...
Dynamic memory allocation is the process by which a program creates and uses memory during runtime. This differs from static memory allocation, where the memory is allocated at compile time.
Dynamic memory allocation involves the following steps:
c
int *ptr = malloc(10);
c
ptr = realloc(ptr, 20);
free function.c
free(ptr);
Benefits of dynamic memory allocation:
Flexibility: Allows programs to allocate and deallocate memory on the fly, which is helpful for handling dynamic data structures.
Performance: Can be faster than static memory allocation, as it avoids the overhead of setting memory at compile time.
Memory efficiency: Allows programs to allocate only the memory they need, reducing memory usage.
Drawbacks of dynamic memory allocation:
Memory leaks: If the program doesn't use all the memory it allocated, it may not be deallocated properly, leading to memory exhaustion.
Dynamic memory allocation can be error-prone: Allocation failures can lead to program crashes or segmentation faults.
Example:
c
// Dynamic memory allocation to an integer
int *ptr = malloc(10);
ptr = "Hello"; // Assigning a string literal to a pointer
// Reallocating memory to a different size
ptr = realloc(ptr, 20);
ptr[10] = 'C'; // Modifying memory dynamically
// Freeing memory allocated with malloc
free(ptr);