C++ Memory Management

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Which of the following is NOT a characteristic of automatic storage duration in C++?

  • Objects are created when defined.
  • Objects are visible within the block of creation.
  • Objects are destroyed automatically at the end of the block.
  • Objects persist until the program ends. (correct)

When does the memory for an object with static storage duration get deallocated?

  • At the end of the block in which it is declared.
  • When it is explicitly deallocated using `delete`.
  • At the end of the program's execution. (correct)
  • At the end of the function in which it is declared.

What is the primary risk associated with dynamic memory allocation in C++?

  • Automatic deallocation by the compiler.
  • Reduced execution speed due to fast access.
  • Memory leaks. (correct)
  • Stack overflow.

Which memory segment is primarily used for storing local variables and function parameters?

<p>Stack segment. (A)</p> Signup and view all the answers

What is the primary purpose of the heap segment in memory management?

<p>Storing dynamically allocated objects. (C)</p> Signup and view all the answers

Which of the following is a characteristic of dynamic objects in C++?

<p>They persist until explicitly destroyed by the programmer. (A)</p> Signup and view all the answers

What is a 'dangling pointer'?

<p>A pointer that points to a memory location that has already been deallocated. (B)</p> Signup and view all the answers

What is the best practice to avoid dangling pointers after deleting dynamically allocated memory?

<p>Set the pointer to <code>nullptr</code> after deleting the memory. (C)</p> Signup and view all the answers

Which code segment contains global and static variables?

<p>Data segment. (A)</p> Signup and view all the answers

In C++, how do you dynamically allocate an array of 10 integers?

<p><code>int* arr = new int[10];</code> (A)</p> Signup and view all the answers

How should a dynamically allocated array be deallocated to prevent memory leaks.

<p><code>delete[] arr;</code> (A)</p> Signup and view all the answers

What is the key difference between owning and non-owning pointers?

<p>Owning pointers are responsible for deallocating the memory they point to. (C)</p> Signup and view all the answers

Which of the following is an advantage of dynamic memory allocation?

<p>Flexibility in allocating memory as needed during runtime. (B)</p> Signup and view all the answers

When the size of a data structure is not known at compile time, which type of memory allocation is more suitable?

<p>Dynamic memory allocation. (A)</p> Signup and view all the answers

Which of the following are true about the stack?

<p>Its size is fixed and relatively small. (C)</p> Signup and view all the answers

Consider the following code snippet:

int* ptr = new int(10);
ptr = nullptr;

Does this code result in a memory leak?

<p>Yes, because the allocated memory is never deallocated. (C)</p> Signup and view all the answers

What would be the output of the following code:

#include <iostream>
using namespace std;

int main() {
    int* ptr = new int(10);
    cout << *ptr << endl;
    delete ptr;
    *ptr = 20;
    cout << *ptr << endl;
    return 0;
}

<p>10\n(undefined behavior) (C)</p> Signup and view all the answers

Consider the following C++ code. Which lines create variables on the heap?

#include <iostream>
using namespace std;

int globalVar; // Line 1

int main() {
    int localVar = 10; // Line 2
    int* dynamicVar = new int(20); // Line 3
    delete dynamicVar; // Line 4
    return 0;
}

<p>Line 3 (D)</p> Signup and view all the answers

Which statement about dangling pointers is correct?

<p>Dangling pointers can cause a program to crash or behave unpredictably. (D)</p> Signup and view all the answers

Given the code:

void f() {
    static int count = 0; // Static variable
    count++;
    cout << "Count: " << count << endl;
}

int main() {
    f();
    f();
    f();
    return 0;
}

What is the output of the code?

<p>Count: 1\nCount: 2\nCount: 3 (B)</p> Signup and view all the answers

Which task does the operating system perform during memory segmentation?

<p>Assigning a portion of total memory to each program under execution. (C)</p> Signup and view all the answers

Which of the following demonstrates how to properly create a dynamic array of pointers to integers with a size of 10?

<p><code>int **arr = new int*[10];</code> (D)</p> Signup and view all the answers

For what is the code segment used?

<p>It contains the code to be executed. (D)</p> Signup and view all the answers

Which is true regarding automatic storage?

<p>Scope is limited to the block i.e. function or loop in which the variable is declared. (A)</p> Signup and view all the answers

Identify the TRUE statements about dynamic storage.

<p>Scope is determined by the pointer referencing the memory. (B)</p> Signup and view all the answers

Flashcards

Object

A region of storage for a given data type.

Automatic Storage

Objects that are created when defined and destroyed at the end of their enclosing block.

Dynamic Storage

Objects that persist in memory until explicitly destroyed by the programmer.

Static Storage

Objects created when the program starts and destroyed when the program ends, persisting between function calls.

Signup and view all the flashcards

Code Segment

Read-only memory area containing the code to be executed.

Signup and view all the flashcards

Data Segment

Memory segment containing global and static variables.

Signup and view all the flashcards

Stack Segment

Memory segment containing local variables and function parameters.

Signup and view all the flashcards

Heap Segment

Memory area reserved for dynamic objects created with new.

Signup and view all the flashcards

Dynamic Objects

Objects stored in the heap without an associated identifier/name.

Signup and view all the flashcards

Memory Leak

Occurs when the address of a dynamic object is lost, making it impossible to destroy and freeing the memory.

Signup and view all the flashcards

Dangling Pointer

A pointer that still points to a memory location that has been deallocated.

Signup and view all the flashcards

Owning Pointer

Pointer that is responsible for deallocating the memory it points to.

Signup and view all the flashcards

Non-Owning Pointer

Pointer that observes or uses the memory but does not deallocate it.

Signup and view all the flashcards

Dynamic memory flexibility

Allow allocation of memory as needed during runtime when the size is unknown at compile time.

Signup and view all the flashcards

What happens when resource management is effective?

Memory can be allocated when needed and deallocated when it's no longer required, resulting in better resource utilization.

Signup and view all the flashcards

When is array local deallocated?

When array is local, it releases it's memory when the function returns or completes

Signup and view all the flashcards

Study Notes

Memory Management Outline

  • Provides an overview of memory management in C++.
  • Details the difference between static and dynamic memory allocation.
  • Discusses storage duration, dynamic objects, and memory leaks.
  • Covers owning versus non-owning objects.
  • Looks at dynamic arrays and structures.

Storage Duration

  • Refers to the lifespan of an object in memory.
  • An object is a region of storage for a given data type.
  • A variable is a named object; for example, int res = 5*5; where res is the name of an int object.
  • Objects can be classified based on their storage duration(Automatic, Dynamic & Static).

Automatic, Dynamic and Static Objects

  • Automatic storage: Objects are created when defined and destroyed at the end of their enclosing block.
    • Local variables are automatic objects, visible within the block of creation and destroyed automatically at the end.
    • E.g., void fun() { int x=12; }
  • Dynamic storage: Dynamic objects persist in memory until explicitly destroyed by the programmer, with storage duration controlled by the programmer.
    • Objects created with new are dynamic objects.
    • Dynamic objects are not destroyed at the end of their enclosing block.
  • Static storage: Objects are created when the program starts and destroyed when the program ends, retaining their value between function calls.
    • Global variables have static storage.
    • Variables declared as static have static storage duration.

Scope and Lifetime of Storage Types

  • Automatic Storage
    • Scope is limited to the block (e.g., function or loop) where the variable is declared.
    • Lifetime exists from the point of declaration until the block is exited.
  • Dynamic Storage
    • Scope is determined by the pointer referencing the memory; the memory is not tied to any block or function.
    • Lifetime lasts from the moment new allocates until delete explicitly deallocates it.
  • Static Storage
    • Scope: Global variables accessible throughout the program; static local variables limited to the function where they're declared.
    • Lifetime exists from program start to program end, regardless of scope.

Memory Segmentation

  • The OS assigns each program under execution (process) a portion of total memory.
  • A process's dedicated address space is divided into four segments: code, data, heap, and stack.
    • Code segment: Read-only memory area containing the code to be executed.
    • Data segment: Contains global and static variables.
      • Global are declared outside any function, class, or block, accessible from anywhere after declaration.
      • Static variables have scope limited to the block in which they are declared but lifetime spans the entire program execution, retaining its value.
    • Stack segment: Contains local variables and function parameters.
    • Heap segment: Reserved for dynamic objects.

Dynamic Objects

  • Dynamic objects stored in the heap are anonymous.
  • Objects created with new are dynamic objects, allocated to a memory address in the heap.
  • The address of a dynamic object is stored in a pointer of the same data type.
    • For example: int *a = new int; *a = 10;

Destroying Dynamic Objects

  • Dynamic objects must be explicitly destroyed with delete.
    • For example:
      • int *a = new int(5);
      • delete a;
  • Memory leaks happen when the address of a dynamic object is lost, making it impossible to destroy it.
    • If dynamically allocated memory isn't freed, it persists in the heap until program completion, wasting memory.
    • Dynamically allocated memory is freed when a program exits.

Owning and Non-Owning Pointers

  • Owning pointer manages the lifetime of the object it points to.
  • Non-owning/observer pointer doesn't manage lifetime.
  • Forgetting to delete an owning pointer creates a memory leak
  • It is better to favour non owning pointers

Dynamic Arrays

  • The new expression creates dynamic arrays.
    • Example: int* arr = new int[5]
  • Initialization is possible using a list initializer.
    • Example: int* arr = new int[5]{1,2,3,4,5}
  • Array is accessed same way as regular arrays.
    • Example: cout<<arr[2];
  • To Delete an array, use delete[] on the array:
    • Example: delete[] arr;
  • Normal arrays are deallocated by the compiler automatically upon the function completing or returning
  • The size of an array with automatic storage (stack-based) must be known at compile time.
  • With dynamic storage, array size can be unknown during compile time.

Stack versus Heap

  • Stack characteristics:
    • Used to manage function calls, local variables, and control flow.
    • Fixed and relatively small size (1 to 8 MB).
    • Fast Access
    • Has automatic memory management.
    • Limited size may lead to stack overflow if too many nested functions or large local variables are used.
  • Heap characteristics:
    • Used for dynamically allocated memory.
    • Size and lifetime determined at runtime
    • Flexible lifetime and big size.
    • Suitable for large dynamic data structures.
    • Slow access (due to pointer access) and risk of data leaks.

Advantages of Dynamic Memory Allocation

  • Flexibility: Allocates memory as needed during runtime, when the size of data structures is unknown or may change during program execution.
  • Data Structures: Supports data structures like linked lists, trees, and resizable arrays that need to accommodate varying amounts of data.
  • Resource Management: Allows allocation when needed and deallocation when no longer required, improving resource utilization.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Gestión de Memoria en C
8 questions

Gestión de Memoria en C

SpiritedKraken9862 avatar
SpiritedKraken9862
CSC 1061: Pointers and Dynamic Memory
20 questions
Use Quizgecko on...
Browser
Browser