Skip to main content

Important Introduction to Programming Short Questions

Chapter: 24
Question 1:
In the given C program, how is dynamic memory used to calculate the average age of students?
Answer: The program dynamically allocates memory for storing the ages of students using malloc, stores the ages using pointer arithmetic, calculates the average, and then frees the allocated memory using free
Chapter: 24
Question 2:
What is the purpose of the realloc function in C?
Answer: The realloc function is used to resize a previously allocated memory block, either enlarging or shrinking it according to new requirements. It reallocates memory while preserving the contents of the original memory.
Chapter: 24
Question 3:
What arguments does the realloc function take?
Answer: The realloc function takes two arguments: a pointer to the previously allocated memory (by malloc or calloc) and the new size in bytes for the memory block.
Chapter: 24
Question 4:
How does realloc behave when there is no contiguous memory available to extend a block?
Answer: If contiguous memory is unavailable, realloc allocates a new memory block, copies the contents of the old memory, and frees the original memory. The pointer is then updated to point to the new memory block.
Chapter: 24
Question 5:
What happens to the original memory block if realloc fails?
Answer: If realloc fails, it returns a NULL pointer, leaving the original memory block unchanged. The programmer must check for NULL before updating the pointer to avoid memory leaks.
Chapter: 24
Question 6:
What is a memory leak?
Answer: A memory leak occurs when allocated memory is no longer referenced by any pointer in the program, making it unusable and wasting system resources. This can lead to system crashes if the heap memory is exhausted.
Chapter: 24
Question 7:
How can memory leaks be prevented in a program?
Answer: Memory leaks can be prevented by ensuring that all allocated memory is freed when no longer needed, particularly within the same function where it was allocated, and by setting freed pointers to NULL.
Chapter: 24
Question 8:
What is a dangling pointer?
Answer: A dangling pointer is a pointer that still references a memory location after the memory has been freed. Using a dangling pointer can lead to undefined behavior, such as program crashes or corrupted data.
Chapter: 24
Question 9:
How do memory leaks differ from dangling pointers?
Answer: Memory leaks result in unused memory that cannot be reclaimed, while dangling pointers reference freed memory that may have been reallocated for other purposes, leading to potential program errors or crashes.
Chapter: 24
Question 10:
What is the recommended practice when using dynamic memory in a program?
Answer: It is recommended to free allocated memory in the same function where it was allocated, check the success of memory allocation immediately, and ensure that all memory is freed before the program exits to avoid memory issues.