Follow us to get updates regarding Latest posts. Follow Now!

Chapter 11: Dynamic Memory Allocation in C

Memory management is an essential aspect of any programming language, and C is no exception. In C, dynamic memory allocation is the process of allocating memory at runtime, as opposed to at compile-time. This allows for more efficient use of memory and enables programs to adapt to changing conditions and requirements.


Dynamic memory allocation in C is performed using four main functions: malloc(), calloc(), realloc(), and free().


  • malloc() function

The malloc() function is used to allocate a block of memory dynamically. It takes a single argument, the size of the block of memory to be allocated in bytes. The function returns a pointer to the first byte of the allocated memory block. If the memory allocation is successful, the function returns a non-null pointer; otherwise, it returns a null pointer.

Example:
C
int *ptr;
ptr = (int *) malloc(100 * sizeof(int));

  • calloc() function 

The calloc() function is used to allocate a block of memory and initialize it to zero. It takes two arguments, the number of elements to be allocated, and the size of each element in bytes. The function returns a pointer to the first byte of the allocated memory block. If the memory allocation is successful, the function returns a non-null pointer; otherwise, it returns a null pointer.
C
int *ptr;
ptr = (int *) calloc(100, sizeof(int));

  • realloc() function

The realloc() function is used to resize an already allocated block of memory. It takes two arguments, pointer to the block of memory to be resized, and the new size of the block in bytes. The function returns a pointer to the first byte of the resized memory block. If the memory reallocation is successful, the function returns a non-null pointer; otherwise, it returns a null pointer.

Example:
C
int *ptr;
ptr = (int *) realloc(ptr, 200 * sizeof(int));

  • free() function 


The free() function is used to deallocate a block of memory that was previously allocated dynamically. It takes a single argument, a pointer to the block of memory to be deallocated. After calling free(), the pointer becomes invalid and should not be used.

Example:



C

free(ptr);



In conclusion, dynamic memory allocation in C provides an essential mechanism for efficiently managing memory in programs. By allocating and deallocating memory at runtime, programs can adapt to changing conditions and requirements, leading to improved performance and flexibility. It is important to keep in mind that dynamically allocated memory must be properly managed to avoid memory leaks and other issues.














Post a Comment

© testsiteweb | All rights reserved

Developed by Jago Desain