CPlusPlus / Memory Management

CPlusPlus / Memory Management#

  1. In which memory region are global variables typically stored?

    In the Initialized Data or Uninitialized Data segment, depending on whether they’re explicitly initialized.

  2. What is the primary difference between stack and heap memory allocation?

    Stack memory is automatically managed and typically used for local variables, while heap memory is manually managed using dynamic allocation.

  3. How do you dynamically allocate an array in C++?

    Using the syntax: type *variableName = new type[numberOfElements];

  4. What is a memory leak, and how can it occur?

    A memory leak occurs when dynamically allocated memory is not properly deallocated. It can happen if you forget to use ‘delete’ after using ‘new’.

  5. What is the difference between passing by value and passing by reference in terms of memory usage?

    Passing by value creates a copy of the object, potentially using more memory, while passing by reference only passes the memory address of the existing object.

  6. What is the purpose of the ‘explicit’ keyword when used with constructors?

    It prevents implicit type conversions, which can help avoid unintended object creation and potential memory issues.

  7. What operators are used to acquire more memory than a program is initially allocated?

    The ‘new’ operator is used in C++ to acquire more memory dynamically. It allocates memory on the heap for objects or arrays. For example:

    int* ptr = new int;  // Allocates memory for a single integer
    int* arr = new int[10];  // Allocates memory for an array of 10 integers
    
  8. What is a dereference operator and why do we need one?

    The dereference operator in C++ is ‘*’. It’s used to access the value stored at the memory address held by a pointer. We need it to interact with the data that a pointer is pointing to, rather than just the memory address itself. For example:

    int* ptr = new int(5);
    int value = *ptr;  // value is now 5