C++ Memory Management MCQs

1 min read

Memory management in C++ empowers developers with direct control over hardware resources, primarily through the allocation and deallocation of memory on the stack and the heap. While the stack automatically manages local variables, the heap requires explicit dynamic memory allocation using the new and delete operators. To mitigate risks like memory leaks and dangling pointers, modern C++ (C++11 and later) strongly advocates for the RAII (Resource Acquisition Is Initialization) idiom. This paradigm relies heavily on smart pointers such as std::unique_ptr, std::shared_ptr, and std::weak_ptr which automate memory cleanup through deterministic destructors. Understanding these mechanisms is crucial for writing efficient, robust, and safe C++ applications.

1. What does the 'new' operator do in C++?

a) Allocates memory and calls the constructor
b) Allocates memory without calling the constructor
c) Calls the constructor without allocating memory
d) Frees previously allocated memory
Correct Answer: a) Allocates memory and calls the constructor
Explanation:
The new operator allocates memory on the heap and then invokes the appropriate constructor for the object.

2. Which operator is used to deallocate memory allocated by 'new'?

a) free
b) delete
c) dealloc
d) release
Correct Answer: b) delete
Explanation:
The delete operator is used to free memory that was allocated using the new operator, and it also calls the destructor.

3. Where are local variables typically stored in C++?

a) Heap
b) Stack
c) Data segment
d) Code segment
Correct Answer: b) Stack
Explanation:
Local variables and function call frames are stored on the call stack, which is managed automatically by the compiler.

4. What exception is thrown by default if 'new' fails to allocate memory?

a) std::memory_error
b) std::allocation_error
c) std::bad_alloc
d) std::out_of_memory
Correct Answer: c) std::bad_alloc
Explanation:
If the new operator cannot allocate the requested memory, it throws a std::bad_alloc exception by default.

5. How can you prevent 'new' from throwing an exception on allocation failure?

a) Use new nofail
b) Use new(std::nothrow)
c) Use new(safe)
d) Use new(false)
Correct Answer: b) Use new(std::nothrow)
Explanation:
Using std::nothrow with the new operator makes it return a null pointer instead of throwing an exception if allocation fails.

6. What is a memory leak?

a) Memory is freed too early
b) Allocated memory is never freed
c) Memory is allocated on the stack instead of the heap
d) Memory is overwritten by another thread
Correct Answer: b) Allocated memory is never freed
Explanation:
A memory leak occurs when dynamically allocated memory is not properly deallocated, leading to wasted memory resources.

7. What is a dangling pointer?

a) A pointer that has not been initialized
b) A pointer that points to freed or deallocated memory
c) A pointer that points to a constant variable
d) A pointer that is used to access array elements
Correct Answer: b) A pointer that points to freed or deallocated memory
Explanation:
A dangling pointer occurs when memory is freed but the pointer still holds the address, leading to undefined behavior if accessed.

8. What is the result of calling 'delete' on the same pointer twice?

a) The program safely ignores the second call
b) A std::double_free exception is thrown
c) Undefined behavior
d) The memory is moved to the stack
Correct Answer: c) Undefined behavior
Explanation:
Calling delete twice on the same pointer results in a double free error, which causes undefined behavior and often crashes the program.

9. Which C-style function allocates memory but does not initialize it?

a) calloc
b) malloc
c) realloc
d) alloc
Correct Answer: b) malloc
Explanation:
The malloc function allocates the specified number of bytes but leaves the memory uninitialized, containing garbage values.

10. Which C-style function allocates memory and initializes it to zero?

a) malloc
b) calloc
c) realloc
d) zero_alloc
Correct Answer: b) calloc
Explanation:
The calloc function allocates memory for an array of elements and initializes all bytes in the allocated storage to zero.

11. What does the 'realloc' function do?

a) Frees memory and allocates new memory
b) Changes the size of a previously allocated memory block
c) Copies memory from one location to another
d) Locks memory to prevent paging
Correct Answer: b) Changes the size of a previously allocated memory block
Explanation:
The realloc function attempts to resize the memory block pointed to by ptr to the given size, preserving existing data when possible.

12. Which header file must be included to use 'malloc' and 'free' in C++?

a) iostream
b) memory
c) cstdlib
d) cstring
Correct Answer: c) cstdlib
Explanation:
The cstdlib header provides the declarations for C-style memory management functions like malloc, calloc, realloc, and free.

13. What is the primary difference between 'new' and 'malloc'?

a) new is faster than malloc
b) new calls constructors, malloc does not
c) malloc allocates on the stack, new on the heap
d) new returns void*, malloc returns a typed pointer
Correct Answer: b) new calls constructors, malloc does not
Explanation:
The new operator not only allocates memory but also invokes the object's constructor, whereas malloc only allocates raw memory.

14. What does RAII stand for in C++?

a) Resource Allocation And Instant Initialization
b) Resource Acquisition Is Initialization
c) Rapid Allocation And Immediate Isolation
d) Recursive Assignment In Inheritance
Correct Answer: b) Resource Acquisition Is Initialization
Explanation:
RAII is a programming idiom where resource allocation is tied to object lifetime, ensuring resources are released when the object is destroyed.

15. Which smart pointer enforces exclusive ownership of a resource?

a) std::shared_ptr
b) std::weak_ptr
c) std::unique_ptr
d) std::auto_ptr
Correct Answer: c) std::unique_ptr
Explanation:
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of it when the unique_ptr goes out of scope, enforcing exclusive ownership.

16. Which smart pointer allows multiple pointers to share ownership of a resource?

a) std::unique_ptr
b) std::shared_ptr
c) std::weak_ptr
d) std::scoped_ptr
Correct Answer: b) std::shared_ptr
Explanation:
std::shared_ptr uses reference counting to allow multiple smart pointers to own the same resource, freeing it when the count reaches zero.

17. Which smart pointer is specifically designed to break cyclic references?

a) std::unique_ptr
b) std::shared_ptr
c) std::weak_ptr
d) std::intrusive_ptr
Correct Answer: c) std::weak_ptr
Explanation:
std::weak_ptr holds a non-owning reference to an object managed by std::shared_ptr, preventing reference cycles that cause memory leaks.

18. What is the recommended way to create a std::unique_ptr?

a) Using the 'new' operator directly
b) Using std::make_unique
c) Using std::make_shared
d) Using malloc
Correct Answer: b) Using std::make_unique
Explanation:
std::make_unique is the recommended way to create a unique_ptr as it provides exception safety and avoids code duplication.

19. What is the main advantage of using std::make_shared over directly using 'new' with std::shared_ptr?

a) It allows custom deleters
b) It allocates the object and control block in a single memory allocation
c) It prevents cyclic references
d) It does not use reference counting
Correct Answer: b) It allocates the object and control block in a single memory allocation
Explanation:
std::make_shared improves performance and memory locality by allocating both the object and its reference counting control block in one operation.

20. What does the Rule of Three state in C++?

a) A class should have three constructors
b) If a class needs a custom destructor, it likely needs a custom copy constructor and copy assignment operator
c) A class should manage exactly three resources
d) A class must have three virtual functions
Correct Answer: b) If a class needs a custom destructor, it likely needs a custom copy constructor and copy assignment operator
Explanation:
The Rule of Three states that if a class requires a custom destructor, copy constructor, or copy assignment operator, it almost certainly requires all three.

21. What additional members does the Rule of Five include compared to the Rule of Three?

a) Move constructor and move assignment operator
b) Default constructor and default destructor
c) Virtual destructor and virtual copy constructor
d) Static constructor and static destructor
Correct Answer: a) Move constructor and move assignment operator
Explanation:
The Rule of Five extends the Rule of Three by adding the move constructor and move assignment operator to handle resource transfer efficiently.

22. What is the Rule of Zero?

a) A class should not have any member variables
b) Classes should rely on the compiler-generated special member functions by using smart pointers and standard containers
c) A class should have zero constructors
d) A class must not use dynamic memory allocation
Correct Answer: b) Classes should rely on the compiler-generated special member functions by using smart pointers and standard containers
Explanation:
The Rule of Zero suggests that classes should not define any of the special member functions if they manage resources using RAII-compliant types like smart pointers.

23. What is 'placement new' used for?

a) Allocating memory on the stack
b) Constructing an object in pre-allocated memory
c) Placing an object in a specific CPU register
d) Allocating memory in a specific memory segment
Correct Answer: b) Constructing an object in pre-allocated memory
Explanation:
Placement new allows you to construct an object at a specific, pre-allocated memory address without allocating new memory.

24. How do you properly clean up an object created with placement new?

a) Use the delete operator
b) Use the free function
c) Explicitly call the destructor
d) It is cleaned up automatically
Correct Answer: c) Explicitly call the destructor
Explanation:
Since placement new does not allocate memory, you must explicitly call the object's destructor to clean it up, and then manually free the underlying memory if needed.

25. What is std::allocator in C++?

a) A smart pointer for arrays
b) The default memory allocator used by standard library containers
c) A function to allocate stack memory
d) A tool for detecting memory leaks
Correct Answer: b) The default memory allocator used by standard library containers
Explanation:
std::allocator is the default allocator used by STL containers to handle memory allocation and deallocation for their elements.

26. What is memory alignment?

a) Sorting memory addresses in ascending order
b) Placing data in memory at addresses that are multiples of the data size
c) Aligning variables alphabetically in the source code
d) Ensuring all variables have the same size
Correct Answer: b) Placing data in memory at addresses that are multiples of the data size
Explanation:
Memory alignment ensures that data is stored at memory addresses that are optimal for the CPU to access, improving performance.

27. What is structure padding?

a) Adding extra members to a struct for documentation
b) Inserting empty bytes between struct members to satisfy alignment requirements
c) Compressing a struct to save memory
d) Aligning the struct name in the code
Correct Answer: b) Inserting empty bytes between struct members to satisfy alignment requirements
Explanation:
Structure padding adds unused bytes between members to ensure each member is properly aligned in memory, which can increase the overall size of the struct.

28. How can you prevent a class from being allocated on the heap?

a) Make the constructor private
b) Make the destructor private
c) Make the new and delete operators private or deleted
d) Use the 'stack' keyword
Correct Answer: c) Make the new and delete operators private or deleted
Explanation:
By making the new and delete operators private or explicitly deleting them, the compiler will prevent objects of the class from being allocated on the heap.

29. What is a memory pool?

a) A large block of memory divided into smaller, fixed-size chunks for fast allocation
b) A pool of shared pointers
c) A collection of memory leaks
d) A method for compressing memory
Correct Answer: a) A large block of memory divided into smaller, fixed-size chunks for fast allocation
Explanation:
A memory pool pre-allocates a large block of memory and divides it into fixed-size chunks, allowing for very fast allocation and deallocation of objects.

30. What typically causes a stack overflow?

a) Allocating too many objects with 'new'
b) Excessive recursion or allocating very large local arrays
c) Using too many smart pointers
d) Calling 'delete' too many times
Correct Answer: b) Excessive recursion or allocating very large local arrays
Explanation:
Stack overflow occurs when the call stack exceeds its maximum size, usually due to deep recursion or allocating large arrays as local variables.

31. What is the behavior of 'delete' when called on a null pointer?

a) Throws a null_pointer exception
b) Causes a segmentation fault
c) Does nothing safely
d) Frees the first byte of memory
Correct Answer: c) Does nothing safely
Explanation:
Calling delete on a null pointer is perfectly safe in C++; the standard specifies that it simply does nothing.

32. What is the difference between 'delete' and 'delete[]'?

a) delete is for single objects, delete[] is for arrays
b) delete is faster than delete[]
c) delete[] is for single objects, delete is for arrays
d) There is no difference
Correct Answer: a) delete is for single objects, delete[] is for arrays
Explanation:
The delete operator is used to free memory for a single object, while delete[] is used to free memory allocated for an array of objects.

33. What happens if you use 'delete' instead of 'delete[]' on an array?

a) The compiler automatically corrects it
b) Only the first element is deleted
c) Undefined behavior
d) A std::bad_array exception is thrown
Correct Answer: c) Undefined behavior
Explanation:
Using delete instead of delete[] on an array results in undefined behavior because the destructors for the remaining elements are not called and memory may not be freed correctly.

34. Which header file provides smart pointers in C++11 and later?

a) smartptr
b) memory
c) pointer
d) utility
Correct Answer: b) memory
Explanation:
The header contains the definitions for smart pointers like std::unique_ptr, std::shared_ptr, and std::weak_ptr.

35. What is stored in the control block of a std::shared_ptr?

a) Only the pointer to the object
b) The reference count, weak count, and custom deleter
c) The object's data members
d) The memory address of the stack frame
Correct Answer: b) The reference count, weak count, and custom deleter
Explanation:
The control block of a shared_ptr manages the reference counts (strong and weak) and stores the custom deleter if one is provided.

36. Can a std::weak_ptr be dereferenced directly using the '*' operator?

a) Yes, always
b) Yes, if it is not expired
c) No, it must be locked to a shared_ptr first
d) No, weak_ptr cannot be dereferenced at all
Correct Answer: c) No, it must be locked to a shared_ptr first
Explanation:
A weak_ptr cannot be dereferenced directly; you must call its lock() method to obtain a shared_ptr, which can then be safely dereferenced.

37. What does the lock() method of a std::weak_ptr return?

a) A raw pointer to the object
b) A std::shared_ptr if the object exists, or an empty shared_ptr if expired
c) A boolean indicating if the object exists
d) A std::unique_ptr
Correct Answer: b) A std::shared_ptr if the object exists, or an empty shared_ptr if expired
Explanation:
The lock() method attempts to create a shared_ptr from the weak_ptr, returning an empty shared_ptr if the managed object has already been destroyed.

38. What is the primary purpose of move semantics in C++?

a) To move variables between threads
b) To transfer resources from one object to another without copying
c) To move objects from the heap to the stack
d) To move memory from RAM to disk
Correct Answer: b) To transfer resources from one object to another without copying
Explanation:
Move semantics allow resources (like dynamically allocated memory) to be transferred from a temporary object to a new object, avoiding expensive deep copies.

39. What does std::move actually do?

a) Moves the object in memory
b) Casts its argument to an rvalue reference
c) Frees the object's memory
d) Copies the object to a new location
Correct Answer: b) Casts its argument to an rvalue reference
Explanation:
std::move does not move anything itself; it simply casts its argument to an rvalue reference, enabling the compiler to invoke move constructors or move assignment operators.

40. What is copy elision?

a) The compiler omitting copy or move constructors in certain situations
b) Deleting the copy constructor manually
c) Copying only the pointer instead of the object
d) Preventing objects from being copied
Correct Answer: a) The compiler omitting copy or move constructors in certain situations
Explanation:
Copy elision is an optimization where the compiler omits copy and move constructors, constructing the object directly in the target memory location.

41. What does RVO stand for?

a) Return Value Optimization
b) Recursive Variable Overloading
c) Reference Variable Optimization
d) Runtime Value Observation
Correct Answer: a) Return Value Optimization
Explanation:
RVO is a compiler optimization technique that eliminates unnecessary copying of objects when they are returned by value from a function.

42. What is NRVO?

a) Named Return Value Optimization
b) New Return Value Operator
c) Non-Recursive Variable Optimization
d) Native Runtime Value Optimization
Correct Answer: a) Named Return Value Optimization
Explanation:
NRVO is a specific form of RVO where the returned object is a named local variable, allowing the compiler to construct it directly in the caller's memory.

43. What is a custom deleter in the context of smart pointers?

a) A function that deletes the smart pointer itself
b) A user-defined function or lambda used to release the managed resource
c) A method to delete multiple objects at once
d) A tool to detect memory leaks
Correct Answer: b) A user-defined function or lambda used to release the managed resource
Explanation:
A custom deleter allows you to specify how the managed resource should be released, useful for resources that require specific cleanup functions like fclose or free.

44. Can std::unique_ptr use a custom deleter?

a) No, it only uses the default delete operator
b) Yes, it can take a custom deleter as a template parameter or constructor argument
c) Only if the object is an array
d) Only in C++20 and later
Correct Answer: b) Yes, it can take a custom deleter as a template parameter or constructor argument
Explanation:
std::unique_ptr supports custom deleters, which are stored as part of the unique_ptr object and invoked when the resource is released.

45. Does std::make_unique support custom deleters directly?

a) Yes, as a second argument
b) No, you must construct the unique_ptr directly to use a custom deleter
c) Yes, using a template specialization
d) Only for array types
Correct Answer: b) No, you must construct the unique_ptr directly to use a custom deleter
Explanation:
std::make_unique does not support custom deleters; to use a custom deleter with unique_ptr, you must construct it directly using the new operator or a raw pointer.

46. What is the size of an empty class in C++?

a) 0 bytes
b) 1 byte
c) 4 bytes
d) 8 bytes
Correct Answer: b) 1 byte
Explanation:
An empty class in C++ has a size of at least 1 byte to ensure that every object has a unique memory address.

47. Why does an empty class have a size of 1 byte?

a) To store a hidden virtual table pointer
b) To ensure that two distinct objects have distinct memory addresses
c) Because the compiler adds a default integer member
d) To align the class to a 1-byte boundary
Correct Answer: b) To ensure that two distinct objects have distinct memory addresses
Explanation:
If an empty class had a size of 0, an array of such objects would have all elements at the same address, violating the requirement that distinct objects have distinct addresses.

48. How does the 'noexcept' specifier help with memory management during moves?

a) It prevents memory leaks by automatically freeing memory
b) It allows containers to use move operations safely without risking exceptions during reallocation
c) It disables the move constructor
d) It forces the use of copy operations
Correct Answer: b) It allows containers to use move operations safely without risking exceptions during reallocation
Explanation:
Marking move constructors as noexcept guarantees they won't throw, allowing standard containers to use them during reallocation, which is faster and provides strong exception safety.

49. What happens if a move constructor throws an exception and it is marked 'noexcept'?

a) The exception is caught and ignored
b) The program terminates immediately
c) The object is copied instead
d) A std::bad_move exception is thrown
Correct Answer: b) The program terminates immediately
Explanation:
If a function marked noexcept throws an exception, the C++ runtime calls std::terminate, immediately ending the program.

50. What is the purpose of the std::align function?

a) To sort an array in memory
b) To adjust a pointer to a specified alignment boundary
c) To compress memory
d) To check if memory is encrypted
Correct Answer: b) To adjust a pointer to a specified alignment boundary
Explanation:
std::align adjusts a pointer to the next address that satisfies a specified alignment requirement, reducing the available space accordingly.

51. What is a slab allocator?

a) An allocator that only allocates memory in multiples of 1MB
b) An allocator that manages memory in fixed-size chunks or slabs
c) An allocator used exclusively for stack memory
d) An allocator that compresses memory
Correct Answer: b) An allocator that manages memory in fixed-size chunks or slabs
Explanation:
A slab allocator pre-allocates memory in large slabs and then divides them into fixed-size chunks, providing fast allocation for objects of a specific size.

52. What is the purpose of std::allocator_traits?

a) To measure memory usage
b) To provide a standardized interface for querying and using custom allocators
c) To delete allocators
d) To convert allocators to smart pointers
Correct Answer: b) To provide a standardized interface for querying and using custom allocators
Explanation:
std::allocator_traits provides a uniform way to access the properties and operations of any allocator, filling in default behaviors if the allocator doesn't define them.

53. What is the 'rebind' mechanism in C++ allocators?

a) Changing the size of an allocated block
b) Creating an allocator for a different type from an existing allocator
c) Binding an allocator to a specific thread
d) Releasing memory back to the OS
Correct Answer: b) Creating an allocator for a different type from an existing allocator
Explanation:
The rebind mechanism allows an allocator designed for one type to be used to allocate memory for a different type, which is essential for containers like std::list.

54. What is a memory fence (or memory barrier)?

a) A physical barrier preventing memory access
b) An instruction that enforces an ordering constraint on memory operations
c) A tool to detect memory leaks
d) A method for encrypting memory
Correct Answer: b) An instruction that enforces an ordering constraint on memory operations
Explanation:
A memory fence ensures that memory operations before the fence are completed before any operations after the fence, crucial for thread synchronization.

55. What is cache locality?

a) Storing data in a local variable
b) Organizing data in memory so that related data is stored close together
c) Using a local cache server
d) Encrypting data in the cache
Correct Answer: b) Organizing data in memory so that related data is stored close together
Explanation:
Cache locality refers to accessing data that is physically close in memory, which increases the likelihood of cache hits and improves performance.

56. How does good cache locality affect program performance?

a) It decreases performance by increasing memory usage
b) It has no effect on performance
c) It significantly improves performance by reducing cache misses
d) It only affects compilation time
Correct Answer: c) It significantly improves performance by reducing cache misses
Explanation:
Good cache locality ensures that data needed together is loaded into the CPU cache together, reducing slow main memory accesses and speeding up execution.

57. What is false sharing in multithreading?

a) Two threads sharing the same smart pointer
b) Two threads modifying independent variables that reside on the same cache line
c) Sharing memory between processes
d) Using the same memory allocator in different threads
Correct Answer: b) Two threads modifying independent variables that reside on the same cache line
Explanation:
False sharing occurs when threads on different cores modify variables that share the same cache line, causing unnecessary cache invalidations and performance degradation.

58. How can you avoid false sharing?

a) By using global variables
b) By aligning thread-local data to the cache line size
c) By using more threads
d) By disabling the CPU cache
Correct Answer: b) By aligning thread-local data to the cache line size
Explanation:
Aligning data structures to the cache line size ensures that each thread modifies its own cache line, preventing false sharing.

59. What does the 'alignas' specifier do?

a) Checks the alignment of a variable
b) Specifies the alignment requirement for a variable or type
c) Aligns the source code formatting
d) Converts a variable to an aligned type
Correct Answer: b) Specifies the alignment requirement for a variable or type
Explanation:
The alignas specifier is used to specify a custom alignment requirement for a variable, class, or struct, overriding the default alignment.

60. What does the 'alignof' operator return?

a) The size of the type in bytes
b) The alignment requirement of the type in bytes
c) The memory address of the type
d) The number of members in the type
Correct Answer: b) The alignment requirement of the type in bytes
Explanation:
The alignof operator returns the alignment requirement of the specified type or expression, which is the number of bytes between successive addresses at which the object can be allocated.

61. What is a memory-mapped file?

a) A file that contains a map of memory addresses
b) A file whose contents are mapped directly into the virtual address space of a process
c) A file used to store memory leaks
d) A compressed memory file
Correct Answer: b) A file whose contents are mapped directly into the virtual address space of a process
Explanation:
A memory-mapped file allows a process to access the file's contents directly in memory as if it were an array, improving I/O performance.

62. Which POSIX function is commonly used to map memory in C++ on Unix-like systems?

a) map_memory
b) mmap
c) alloc_map
d) virtual_map
Correct Answer: b) mmap
Explanation:
The mmap function is used in POSIX systems to map files or devices into memory, allowing direct memory access to file contents.

63. What is virtual memory?

a) Memory stored in a virtual machine
b) An abstraction that gives each process the illusion of a large, contiguous block of memory
c) Memory allocated using virtual functions
d) Memory that exists only in the source code
Correct Answer: b) An abstraction that gives each process the illusion of a large, contiguous block of memory
Explanation:
Virtual memory is a memory management technique where the OS uses hardware to map virtual addresses used by a process to physical addresses in RAM or on disk.

64. What is a page fault?

a) An error in the page allocation algorithm
b) An interrupt raised when a program accesses a memory page that is not currently in physical RAM
c) A syntax error in the code
d) A failure to allocate stack memory
Correct Answer: b) An interrupt raised when a program accesses a memory page that is not currently in physical RAM
Explanation:
A page fault occurs when a program tries to access a block of memory that is mapped in the virtual address space but not currently loaded in physical RAM, prompting the OS to load it.

65. What is thrashing in the context of memory management?

a) Rapidly allocating and freeing small memory blocks
b) Excessive paging activity where the OS spends more time swapping pages than executing processes
c) Deleting memory too quickly
d) Using too many threads
Correct Answer: b) Excessive paging activity where the OS spends more time swapping pages than executing processes
Explanation:
Thrashing occurs when the system's virtual memory subsystem is constantly swapping pages in and out of RAM, severely degrading performance.

66. What is the difference between the 'new' expression and 'operator new'?

a) They are exactly the same
b) The new expression allocates memory and calls the constructor; operator new only allocates memory
c) operator new allocates memory and calls the constructor; new only allocates memory
d) The new expression is for arrays, operator new is for single objects
Correct Answer: b) The new expression allocates memory and calls the constructor; operator new only allocates memory
Explanation:
The new expression is a language feature that calls operator new to allocate raw memory and then invokes the constructor, while operator new is just the memory allocation function.

67. How can you overload the 'operator new' for a specific class?

a) By defining a global function named new
b) By providing a static member function named operator new in the class
c) By using the #define directive
d) It cannot be overloaded for a specific class
Correct Answer: b) By providing a static member function named operator new in the class
Explanation:
You can overload operator new for a specific class by defining it as a static member function, which will be called when objects of that class are allocated with new.

68. What is the standard signature for the global 'operator new' function?

a) void operator new(size_t size)
b) void* operator new(size_t size)
c) int operator new(size_t size)
d) char* operator new(size_t size)
Correct Answer: b) void* operator new(size_t size)
Explanation:
The global operator new function takes a size_t parameter representing the number of bytes to allocate and returns a void pointer to the allocated memory.

69. What is 'operator new[]' used for?

a) Allocating memory for a single object
b) Allocating memory for an array of objects
c) Deleting an array of objects
d) Copying an array of objects
Correct Answer: b) Allocating memory for an array of objects
Explanation:
operator new[] is called by the new[] expression to allocate raw memory for an array of objects before their constructors are invoked.

70. What is a memory barrier?

a) A physical limit on memory size
b) A mechanism to prevent the compiler and CPU from reordering memory operations across the barrier
c) A tool to block memory leaks
d) A type of smart pointer
Correct Answer: b) A mechanism to prevent the compiler and CPU from reordering memory operations across the barrier
Explanation:
A memory barrier ensures that memory operations issued before the barrier are completed before any operations after the barrier, maintaining correct execution order in concurrent programs.

71. What is std::atomic in C++?

a) A class for managing atomic memory allocation
b) A template class that provides atomic operations for fundamental types
c) A smart pointer for atomic objects
d) A function to compress memory
Correct Answer: b) A template class that provides atomic operations for fundamental types
Explanation:
std::atomic is a template class that ensures operations on the contained value are performed atomically, making them thread-safe without explicit locks.

72. How does std::atomic relate to memory management in concurrent programming?

a) It automatically frees memory when threads finish
b) It ensures thread-safe access to shared memory without data races
c) It allocates memory atomically
d) It compresses memory atomically
Correct Answer: b) It ensures thread-safe access to shared memory without data races
Explanation:
std::atomic provides thread-safe operations on shared memory locations, preventing data races and ensuring consistent state across multiple threads.

73. What is a memory order in the context of std::atomic?

a) The sequence in which memory is allocated
b) A constraint on how memory operations around atomic operations are ordered and visible to other threads
c) The size of the atomic variable
d) The type of the atomic variable
Correct Answer: b) A constraint on how memory operations around atomic operations are ordered and visible to other threads
Explanation:
Memory order specifies the synchronization and ordering constraints on memory operations, controlling how and when changes to atomic variables become visible to other threads.

74. What does memory_order_relaxed mean?

a) Strict ordering of all memory operations
b) No synchronization or ordering constraints, only atomicity is guaranteed
c) Memory is released immediately
d) Memory is allocated on the stack
Correct Answer: b) No synchronization or ordering constraints, only atomicity is guaranteed
Explanation:
memory_order_relaxed provides atomicity and ordering guarantees only for the atomic variable itself, with no synchronization constraints on surrounding memory operations.

75. What does memory_order_seq_cst mean?

a) The weakest memory ordering
b) Sequential consistency, providing the strongest ordering guarantees
c) Memory is allocated sequentially
d) Memory is compressed sequentially
Correct Answer: b) Sequential consistency, providing the strongest ordering guarantees
Explanation:
memory_order_seq_cst ensures that all threads see all modifications in the same order, providing the strictest synchronization and ordering guarantees.

76. What is a memory sanitizer?

a) A tool to clean up memory leaks
b) A compiler or runtime tool that detects memory errors like buffer overflows and use-after-free
c) A function to free memory safely
d) A type of smart pointer
Correct Answer: b) A compiler or runtime tool that detects memory errors like buffer overflows and use-after-free
Explanation:
Memory sanitizers are tools that instrument code to detect various memory-related errors during execution, helping to identify bugs that cause crashes or security vulnerabilities.

77. What does AddressSanitizer (ASan) primarily detect?

a) Uninitialized memory reads
b) Buffer overflows, use-after-free, and memory leaks
c) Thread deadlocks
d) Syntax errors
Correct Answer: b) Buffer overflows, use-after-free, and memory leaks
Explanation:
AddressSanitizer is a fast memory error detector that finds out-of-bounds accesses, use-after-free bugs, and memory leaks.

78. What does MemorySanitizer (MSan) detect?

a) Memory leaks
b) Reads of uninitialized memory
c) Buffer overflows
d) Use-after-free errors
Correct Answer: b) Reads of uninitialized memory
Explanation:
MemorySanitizer is a detector of uninitialized memory reads, which can lead to unpredictable behavior and security vulnerabilities.

79. What does LeakSanitizer (LSan) detect?

a) Buffer overflows
b) Uninitialized memory reads
c) Memory leaks
d) Thread race conditions
Correct Answer: c) Memory leaks
Explanation:
LeakSanitizer is a runtime memory leak detector that identifies dynamically allocated memory that was not properly freed before the program exited.

80. What is Valgrind?

a) A C++ compiler
b) A programming tool for memory debugging, memory leak detection, and profiling
c) A smart pointer library
d) A memory allocation function
Correct Answer: b) A programming tool for memory debugging, memory leak detection, and profiling
Explanation:
Valgrind is an instrumentation framework for building dynamic analysis tools, commonly used to detect memory management and threading bugs in C++ programs.

81. How does 'malloc' differ from 'new' regarding type safety?

a) malloc is more type-safe than new
b) new is type-safe and returns a correctly typed pointer, while malloc returns void*
c) Both are equally type-safe
d) Neither is type-safe
Correct Answer: b) new is type-safe and returns a correctly typed pointer, while malloc returns void*
Explanation:
The new operator returns a pointer of the correct type, ensuring type safety, whereas malloc returns a void pointer that must be explicitly cast, which can lead to type errors.

82. What is the return type of the 'malloc' function?

a) int*
b) char*
c) void*
d) The type of the variable being allocated
Correct Answer: c) void*
Explanation:
The malloc function returns a void pointer (void*) to the allocated memory, which must be cast to the appropriate pointer type in C (though not required in C++).

83. What is the return type of the 'new' operator?

a) void*
b) A pointer to the allocated type
c) int
d) bool
Correct Answer: b) A pointer to the allocated type
Explanation:
The new operator returns a pointer of the exact type being allocated, providing type safety without the need for explicit casting.

84. What is the memory overhead of a std::shared_ptr's control block?

a) Zero overhead
b) Extra memory to store the strong reference count, weak reference count, and deleter
c) Only the size of the object itself
d) A fixed 1 byte
Correct Answer: b) Extra memory to store the strong reference count, weak reference count, and deleter
Explanation:
The control block of a shared_ptr requires additional memory to manage reference counts and store the custom deleter, adding overhead compared to raw pointers.

85. How can you reduce the memory overhead of std::shared_ptr?

a) By using std::unique_ptr instead
b) By using std::make_shared to allocate the object and control block together
c) By disabling reference counting
d) By using raw pointers
Correct Answer: b) By using std::make_shared to allocate the object and control block together
Explanation:
std::make_shared reduces memory overhead and improves locality by allocating the object and its control block in a single memory allocation, rather than two separate ones.

86. What is an intrusive smart pointer?

a) A smart pointer that modifies the object's internal state
b) A smart pointer where the reference count is stored inside the managed object itself
c) A smart pointer that cannot be copied
d) A smart pointer that uses a custom allocator
Correct Answer: b) A smart pointer where the reference count is stored inside the managed object itself
Explanation:
In an intrusive smart pointer, the managed object contains the reference count as a member, eliminating the need for a separate control block and reducing memory overhead.

87. Which Boost library provides intrusive smart pointers?

a) boost::smart_ptr
b) boost::intrusive_ptr
c) boost::shared_ptr
d) boost::memory
Correct Answer: b) boost::intrusive_ptr
Explanation:
The Boost library provides boost::intrusive_ptr, an intrusive reference-counting smart pointer where the reference count is managed by the object itself.

88. What is the purpose of std::owner_less?

a) To compare the values of two shared pointers
b) To provide a strict weak ordering for weak_ptr and shared_ptr based on ownership, not value
c) To delete the owner of a pointer
d) To lock a weak pointer
Correct Answer: b) To provide a strict weak ordering for weak_ptr and shared_ptr based on ownership, not value
Explanation:
std::owner_less is a function object that compares shared_ptr and weak_ptr based on their ownership (control block address) rather than the value of the managed object, useful for associative containers.

89. What does std::enable_shared_from_this allow an object to do?

a) Enable the object to be copied
b) Allow the object to safely generate a std::shared_ptr to itself
c) Enable the object to be moved
d) Allow the object to be allocated on the stack
Correct Answer: b) Allow the object to safely generate a std::shared_ptr to itself
Explanation:
Inheriting from std::enable_shared_from_this allows an object to create a shared_ptr to itself, ensuring that the reference count is correctly updated and the object is not deleted prematurely.

90. What happens if shared_from_this() is called on an object that is not currently managed by a std::shared_ptr?

a) It returns a null pointer
b) It throws a std::bad_weak_ptr exception
c) It creates a new shared_ptr
d) It causes a segmentation fault
Correct Answer: b) It throws a std::bad_weak_ptr exception
Explanation:
If shared_from_this() is called when no shared_ptr currently owns the object, it throws a std::bad_weak_ptr exception because the internal weak_ptr is empty.

91. What is a memory arena?

a) A small block of memory for single objects
b) A large contiguous block of memory from which smaller allocations are made
c) A type of smart pointer
d) A tool for detecting memory leaks
Correct Answer: b) A large contiguous block of memory from which smaller allocations are made
Explanation:
A memory arena is a large, pre-allocated block of memory used to satisfy many smaller allocation requests, simplifying memory management and improving performance.

92. What is the primary benefit of using a memory arena?

a) It allows individual objects to be freed easily
b) Fast allocation and the ability to free all allocated memory at once
c) It prevents memory leaks automatically
d) It compresses memory
Correct Answer: b) Fast allocation and the ability to free all allocated memory at once
Explanation:
Memory arenas provide very fast allocation by simply incrementing a pointer, and allow all allocated memory to be freed simultaneously by resetting the arena, avoiding individual deallocation overhead.

93. What is a bump allocator?

a) An allocator that uses a bump mapping technique
b) A simple allocator that satisfies allocations by incrementing a pointer
c) An allocator that bumps the priority of threads
d) An allocator that compresses memory
Correct Answer: b) A simple allocator that satisfies allocations by incrementing a pointer
Explanation:
A bump allocator (or linear allocator) satisfies memory requests by simply moving a pointer forward, making it extremely fast but unable to free individual allocations.

94. What is the main drawback of a bump allocator?

a) It is very slow
b) It cannot free individual objects, only the entire arena
c) It uses too much memory
d) It is not thread-safe
Correct Answer: b) It cannot free individual objects, only the entire arena
Explanation:
Because a bump allocator only moves a pointer forward, it has no mechanism to track and free individual allocations; memory can only be reclaimed by resetting the entire arena.

95. What is std::pmr in C++17?

a) Polymorphic Memory Resource
b) Private Memory Region
c) Protected Memory Reference
d) Persistent Memory Repository
Correct Answer: a) Polymorphic Memory Resource
Explanation:
std::pmr stands for Polymorphic Memory Resource, a library that provides a unified interface for different memory allocation strategies, allowing containers to use custom allocators seamlessly.

96. What is std::pmr::monotonic_buffer_resource?

a) A resource that frees memory immediately after use
b) A memory resource that never frees individual allocations until the resource itself is destroyed
c) A resource that compresses memory
d) A resource that allocates memory on the stack
Correct Answer: b) A memory resource that never frees individual allocations until the resource itself is destroyed
Explanation:
monotonic_buffer_resource is a type of memory arena that allocates memory monotonically and only releases all memory when the resource object is destroyed, making it very fast for temporary allocations.

97. What is std::pmr::unsynchronized_pool_resource?

a) A thread-safe memory pool
b) A memory pool that is not thread-safe and intended for single-threaded use
c) A resource that synchronizes threads
d) A resource that compresses memory
Correct Answer: b) A memory pool that is not thread-safe and intended for single-threaded use
Explanation:
unsynchronized_pool_resource is a memory pool that does not use internal synchronization, making it faster for single-threaded applications but unsafe for concurrent access.

98. What is the default memory resource used by std::pmr containers?

a) std::pmr::null_memory_resource
b) std::pmr::new_delete_resource
c) std::pmr::monotonic_buffer_resource
d) std::pmr::pool_resource
Correct Answer: b) std::pmr::new_delete_resource
Explanation:
The default memory resource for std::pmr containers is std::pmr::new_delete_resource, which uses the standard global new and delete operators for memory allocation and deallocation.
← Previous: C++ Loops (For, While)
Next →: C++ OOP MCQs Object-Oriented Programming
NewC++ Constructors and Destructors MCQs

C++ Constructors and Destructors MCQs

In C++, constructors and destructors are special member functions critical for the Resource Acquisition Is Initialization (RAII) paradigm and safe…

By MCQs Generator
New
No Image

400+ C++ Interview Questions MCQ

1. What does the 'new' operator do in C++? a) Allocates memory and calls the constructor b) Allocates memory without…

By MCQs Generator
New
No Image

C++ Arrays / Lists - MCQs

1. What does the 'new' operator do in C++? a) Allocates memory and calls the constructor b) Allocates memory without…

By MCQs Generator