Memory management in C++ is a fundamental concept that every developer should understand. By correctly managing memory, developers can ensure optimal performance and prevent memory leaks and other related issues.
The primary tools in C++ for memory management are pointers, dynamic allocation, and deallocation. If you’re starting with C++ or need a refresher, this quiz will help you gauge your understanding of C++ memory management.
1. Which of the following is used to dynamically allocate a single variable in C++?
Answer:
Explanation:
In C++, the new operator is primarily used to allocate memory for a variable or an array of variables.
2. How do you deallocate memory assigned by the new operator?
Answer:
Explanation:
The delete operator is used to deallocate memory that was previously allocated by the new operator.
3. Which function in C++ is used to dynamically allocate memory for an array?
Answer:
Explanation:
new[] is used for dynamic allocation of arrays in C++.
4. What is the main problem with using raw pointers in C++?
Answer:
Explanation:
Raw pointers can lead to memory leaks if not handled correctly, as the programmer is responsible for both allocation and deallocation.
5. What does a pointer variable store?
Answer:
Explanation:
A pointer stores the address of another variable.
6. Which of the following is not a type of pointer?
Answer:
Explanation:
There is no concept called a “Real pointer” in C++.
7. What will happen if you forget to deallocate dynamically allocated memory?
Answer:
Explanation:
Forgetting to deallocate dynamically allocated memory results in a memory leak.
8. In which section of memory are local variables stored?
Answer:
Explanation:
Local variables are typically stored in the stack memory.
9. How can you allocate memory for a 2D array in C++?
Answer:
Explanation:
To allocate memory for a 2D array, you can use new int[x][y].
10. Which of these is the correct way to declare a pointer to an integer?
Answer:
Explanation:
The correct way to declare a pointer to an integer is int *p;.