C++ Memory Management MCQ

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++?

a) malloc()
b) new
c) alloc
d) calloc()

Answer:

b) new

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?

a) free()
b) delete
c) remove()
d) dealloc

Answer:

b) delete

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?

a) malloc()
b) new[]
c) alloc[]
d) calloc()

Answer:

b) new[]

Explanation:

new[] is used for dynamic allocation of arrays in C++.

4. What is the main problem with using raw pointers in C++?

a) Performance overhead
b) Memory leaks
c) Reduced flexibility
d) Slower execution

Answer:

b) Memory leaks

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?

a) A value
b) A function
c) Address of another variable
d) Size of memory

Answer:

c) Address of another variable

Explanation:

A pointer stores the address of another variable.

6. Which of the following is not a type of pointer?

a) Wild pointer
b) Null pointer
c) Real pointer
d) Dangling pointer

Answer:

c) Real pointer

Explanation:

There is no concept called a “Real pointer” in C++.

7. What will happen if you forget to deallocate dynamically allocated memory?

a) Syntax error
b) Runtime error
c) Memory leak
d) Logic error

Answer:

c) Memory leak

Explanation:

Forgetting to deallocate dynamically allocated memory results in a memory leak.

8. In which section of memory are local variables stored?

a) Heap
b) Stack
c) Data
d) Code

Answer:

b) Stack

Explanation:

Local variables are typically stored in the stack memory.

9. How can you allocate memory for a 2D array in C++?

a) new [x][y]
b) new x*y
c) new [x]*[y]
d) new int[x][y]

Answer:

d) new int[x][y]

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?

a) int p*;
b) *p int;
c) int *p;
d) p* int;

Answer:

c) int *p;

Explanation:

The correct way to declare a pointer to an integer is int *p;.


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top