What is dynamic memory allocation in C, and how is it used to allocate memory at runtime?
What is dynamic memory allocation in C, and how is it used to allocate memory at runtime?
35921-Apr-2023
Updated on 22-Apr-2023
Aryan Kumar
22-Apr-2023Dynamic memory allocation is the process of allocating memory at runtime in C. Unlike static memory allocation, where memory is allocated at compile-time, dynamic memory allocation allows the programmer to allocate and deallocate memory as needed during program execution.
In C, dynamic memory allocation is achieved using four functions from the standard library: malloc, calloc, realloc, and free. Here's how each function works:
malloc: 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 fails (due to insufficient memory), malloc returns NULL.
Example: To allocate a block of 100 bytes of memory at runtime, you can use the following code:
calloc: Allocates a block of memory of the specified size (in bytes) and initializes all the bytes to zero. The calloc function takes two arguments: the number of elements to allocate and the size of each element (in bytes).
Example: To allocate an array of 10 integers and initialize all the elements to zero, you can use the following code:
realloc: Reallocates a previously allocated block of memory to a new size. If the new size is smaller than the original size, the extra memory is freed. If the new size is larger than the original size, additional memory is allocated. The contents of the old block are copied to the new block, and the old block is freed. If the allocation fails, realloc returns NULL and the original block is left unchanged.
Example: To reallocate the block of memory pointed to by ptr to a new size of 200 bytes, you can use the following code:
free: Frees a block of memory that was previously allocated with malloc, calloc, or realloc. The pointer to the block of memory is passed as an argument to free.
Example: To free the block of memory pointed to by ptr, you can use the following code:
When using dynamic memory allocation in C, it's important to manage memory carefully to avoid memory leaks and other issues. Always free memory when it's no longer needed, and be careful not to access memory that has already been freed.