Memory Management Functions in C

In C, memory management functions are used to allocate, deallocate, and manage memory dynamically during program execution. The most commonly used memory management functions in C are `malloc()`, `calloc()`, `realloc()`, and `free()`.

1. `malloc()` function: This function allocates a block of memory of the specified size and returns a pointer to the first byte of the block. The syntax for using `malloc()` is:

void *malloc(size_t size);

Here, `size` is the number of bytes to allocate, and the return value is a void pointer to the allocated memory. We can then cast this pointer to the appropriate data type.

For example, to allocate memory for an integer variable, we can use the following code:

int *p = (int *) malloc(sizeof(int));

2. `calloc()` function: This function is similar to `malloc()`, but it initializes the allocated memory to zero. The syntax for using `calloc()` is:

void *calloc(size_t num, size_t size);

Here, `num` is the number of elements to allocate, and `size` is the size of each element. The return value is a void pointer to the allocated memory.

For example, to allocate memory for an array of 10 integers, we can use the following code:

int *p = (int *) calloc(10, sizeof(int));

3. `realloc()` function: This function is used to resize an existing block of memory. The syntax for using `realloc()` is:

void *realloc(void *ptr, size_t size);

Here, `ptr` is a pointer to the existing block of memory, and `size` is the new size of the block. The return value is a void pointer to the resized memory block.

For example, to resize an existing block of memory allocated using `malloc()`, we can use the following code:

int *p = (int *) malloc(sizeof(int));
p = (int *) realloc(p, 10 * sizeof(int));

4. `free()` function: This function is used to deallocate memory that was previously allocated using `malloc()`, `calloc()`, or `realloc()`. The syntax for using `free()` is:

void free(void *ptr);

Here, `ptr` is a pointer to the memory block to deallocate.

For example, to deallocate memory allocated using `malloc()`, we can use the following code:

int *p = (int *) malloc(sizeof(int));
// do some work with p
free(p);

It’s important to note that improper use of memory management functions can lead to memory leaks and other memory-related errors. It’s important to always allocate and deallocate memory properly, and to avoid accessing memory that has been deallocated.