Frequently Asked interview question on dynamic memory management in C,dynamic memory faq in C language

Q5.What are common pitfalls to avoid when working with dynamic memory allocation in C programs?
When working with dynamic memory allocation in C programs, many pitfalls cans must be avoided to ensure efficient and error-free memory management. Some of these pitfalls include:
1. Forgetting to free allocated memory.
2. Accessing memory beyond allocated boundaries.
3. Not checking for NULL after allocation.
4. Mixing up memory allocation functions.
5. Memory fragmentation.


Q6.How does memory leak occur in dynamic memory allocation, and how can it be prevented?
A memory leak in C occurs when a program allocates memory for a data structure, such as list, an array, or tree, but does not release it when it is no longer wanted. This means that the system takings up memory, but other parts of the code cannot reuse or access it.
There is a simple way to avoid memory leaks in programs written in C:
Have 2 global variables (at least 32 bit, but 64 bit is even better). These two variables will be initialized to 0 at the beginning of the program.


Q7.What is the role of the realloc() function in dynamic memory management in C?
The realloc() function is resizeto previously allocated blocks. It takes two arguments: a pointer to the previously allocated memory block and the new size in bytes. The return value is a pointer to an array block, which may or may not be the same as the previous point.


Q8.Can you provide an example of dynamically allocating memory for a data structure like an array or linked list in C?
For example, to allocate an integer array,use
int *arr = (int *) malloc(n * sizeof(int))
or
int *arr = (int *) calloc(n, sizeof(int))
where `n` is the chosen array size. Remember to free the allocated memory using `free()` when it is no longer needed.


Previous Topic:-->>Storage Class FAQ in C. || Next topic:-->>Basic C assignments.