Dynamic memory allocation in C allows you to allocate memory at runtime, rather than at compile-time. This means that you can request memory as your program runs, rather than having to pre-allocate a fixed amount of memory at the start of your program.
In C, dynamic memory allocation is typically performed using the functions `malloc()`, `calloc()`, and `realloc()`.
The `malloc()` function is used to allocate a block of memory of a specified size. It takes a single argument, which is the number of bytes to allocate, and returns a pointer to the first byte of the allocated block. For example, to allocate a block of memory to hold 100 integers, you could use the following code:
int *my_array = (int *)malloc(100 * sizeof(int));
The `calloc()` function is similar to `malloc()`, but it also initializes the allocated memory to zero. It takes two arguments: the number of elements to allocate, and the size of each element. For example:
int *my_array = (int *)calloc(100, sizeof(int));
The `realloc()` function is used to resize an existing block of memory. It takes two arguments: a pointer to the existing block of memory, and the new size of the block. For example:
int *my_array = (int *)malloc(100 * sizeof(int)); my_array = (int *)realloc(my_array, 200 * sizeof(int));
It’s important to remember that when you allocate memory dynamically, you are responsible for freeing it when you are done using it. This is typically done using the `free()` function, which takes a single argument: a pointer to the beginning of the block of memory to free. For example:
int *my_array = (int *)malloc(100 * sizeof(int)); // do some work with my_array free(my_array);
One common mistake with dynamic memory allocation is forgetting to free the memory when you’re done with it. This can lead to memory leaks, where your program continues to use memory even though it no longer needs it. It’s important to make sure that you always free any memory that you allocate dynamically.