This C program demonstrates the use of dynamic memory allocation in C using the malloc() and realloc() functions. The program allocates memory for two integer variables using malloc(), assigns values to them, and then uses realloc() to change the size of the memory block pointed to by one of the pointers.
- Allocate memory for two integer variables using malloc().
- Assign a value to the first variable using the first pointer.
- Increment the first pointer to point to the second variable.
- Assign a value to the second variable using the first pointer.
- Use realloc() to change the size of the memory block pointed to by the first pointer.
- Assign a value to the newly allocated memory location using the new pointer returned by realloc().
Suppose we want to allocate memory for two integer variables, assign them values, and then resize the memory block pointed to by one of the pointers to allocate memory for a single integer variable. The program does the following:
- Allocates memory for two integer variables using malloc().
- Assigns a value of 13 to the first variable using the first pointer.
- Increments the first pointer to point to the second variable.
- Assigns a value of 7 to the second variable using the first pointer.
- Uses realloc() to resize the memory block pointed to by the first pointer to allocate memory for a single integer variable.
- Assigns a value of 5 to the newly allocated memory location using the new pointer returned by realloc().
Dynamic memory allocation is useful in situations where we don't know the size of the data that needs to be stored in memory beforehand. It allows us to allocate memory for data at runtime and release it when it's no longer needed. The malloc() and realloc() functions provide a flexible way to manage memory dynamically.
Dynamic memory allocation is used in a wide variety of applications, such as:
- Implementing data structures like linked lists, stacks, and queues.
- Allocating memory for variables and arrays in programs that need to handle varying amounts of data.
- Implementing dynamic libraries and plugins that can be loaded and unloaded at runtime.