If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C language, dynamic memory allocation is the process of allocating memory at runtime, as opposed to compile-time. This allows a program to acquire more memory as needed, rather than having a fixed amount of memory allocated at the beginning of the program. The standard library provides several functions for dynamic memory allocation:
malloc(size_t size)
: This function allocates a block of memory of the specified size (in bytes) and returns a pointer to the first byte of the block. If the allocation is successful, the pointer is guaranteed to be suitably aligned for any object type. If the allocation fails, malloc
returns a null pointer.Here's an example of how to use malloc
to allocate memory for an array of integers:
Copy code
int* arr = (int*) malloc(10 * sizeof(int));
calloc(size_t nmemb, size_t size)
: This function allocates a block of memory for an array of nmemb
elements, each of size
bytes, and returns a pointer to the first byte of the block. The memory is initialized to zero. If the allocation fails, calloc
returns a null pointer.Here's an example of how to use calloc
to allocate memory for an array of integers:
Copy code
int* arr = (int*) calloc(10, sizeof(int));
free(void* ptr)
: This function frees the memory previously allocated by malloc
or calloc
. Once the memory is freed, the pointer is no longer valid, and attempting to access the memory can result in undefined behavior. It's important to note that you should only free memory that you have allocated dynamically, and not memory allocated by the program or memory on the stack.Here's an example of how to use free
to deallocate memory for an array of integers:
Copy code
int* arr = (int*) malloc(10 * sizeof(
Comments: 0