Bird
Raised Fist0
C++programming~10 mins

Memory allocation and deallocation in C++ - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Memory allocation and deallocation
Start Program
↓
Request Memory Allocation
↓
Memory Allocated
↓
Use Allocated Memory
↓
Request Memory Deallocation
↓
Memory Freed
↓
End Program
The program starts, requests memory from the system, uses it, then frees it before ending.
Execution Sample
C++
#include <iostream>
int main() {
  int* ptr = new int(10);
  std::cout << *ptr << std::endl;
  delete ptr;
  return 0;
}
This code allocates memory for an int, stores 10, prints it, then frees the memory.
Execution Table
StepActionPointer ValueMemory StateOutput
1Allocate memory with new int(10)ptr -> address1Memory block allocated at address1 with value 10
2Dereference ptr to get valueptr -> address1Memory block unchanged10
3Delete ptr to free memoryptr -> address1 (dangling)Memory at address1 freed
4Program endsptr -> address1 (dangling)No allocated memory
💡 Program ends after memory is freed to avoid leaks
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
ptruninitializedaddress1address1dangling pointerdangling pointer
Key Moments - 3 Insights
Why does ptr become a dangling pointer after delete?
After delete, the memory is freed but ptr still holds the old address (see execution_table step 3), so it points to invalid memory.
What happens if we forget to delete the allocated memory?
Memory remains allocated and is not returned to the system, causing a memory leak (not shown in execution_table but implied if step 3 is skipped).
Can we use ptr after deleting it?
No, using ptr after delete leads to undefined behavior because the memory is freed (execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of ptr after step 3?
AA dangling pointer to freed memory
BNull pointer
CUninitialized pointer
DPointer to valid allocated memory
💡 Hint
Check the 'Pointer Value' column at step 3 in execution_table
At which step is the memory actually freed?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Memory State' column for when memory changes from allocated to freed
If we remove the delete statement, what changes in the execution_table?
AOutput changes to 0
Bptr becomes null after step 3
CMemory remains allocated after step 3
DProgram crashes immediately
💡 Hint
Consider what happens if memory is not freed as shown in step 3
Concept Snapshot
Memory allocation uses 'new' to reserve space and returns a pointer.
Use the pointer to access or modify the data.
Free memory with 'delete' to avoid leaks.
After delete, pointer becomes dangling and should not be used.
Always pair new with delete to manage memory safely.
Full Transcript
This example shows how a C++ program allocates memory dynamically using 'new'. The pointer 'ptr' receives the address of the allocated memory holding the value 10. The program prints this value by dereferencing 'ptr'. Then, it frees the memory with 'delete', making 'ptr' a dangling pointer because it still holds the old address but the memory is no longer valid. The program ends after freeing memory to prevent leaks. Beginners often confuse the pointer's state after deletion and the importance of freeing memory to avoid leaks. The visual quiz reinforces understanding of pointer states and memory lifecycle.

Practice

(1/5)
1. What does the new operator do in C++?
easy
A. Allocates memory on the heap for a variable or object
B. Deletes a variable from memory
C. Allocates memory on the stack
D. Copies data from one variable to another

Solution

  1. Step 1: Understand the role of new

    The new operator allocates memory dynamically on the heap during program execution.
  2. Step 2: Differentiate from other memory actions

    It does not delete memory or allocate on the stack; it only reserves space on the heap.
  3. Final Answer:

    Allocates memory on the heap for a variable or object -> Option A
  4. Quick Check:

    new = allocate heap memory [OK]
Hint: Remember: new = allocate memory on heap [OK]
Common Mistakes:
  • Confusing new with delete
  • Thinking new allocates on stack
  • Assuming new copies data
2. Which of the following is the correct syntax to deallocate memory allocated with new for a single integer variable?
easy
A. delete[] ptr;
B. free(ptr);
C. delete ptr;
D. ptr = nullptr;

Solution

  1. Step 1: Identify correct deallocation for single object

    Memory allocated with new for a single variable must be freed with delete, not delete[].
  2. Step 2: Exclude incorrect options

    free() is for C-style malloc, and setting pointer to nullptr does not free memory.
  3. Final Answer:

    delete ptr; -> Option C
  4. Quick Check:

    Single object deallocation = delete [OK]
Hint: Use delete for single object, delete[] for arrays [OK]
Common Mistakes:
  • Using delete[] for single variable
  • Using free() instead of delete
  • Only setting pointer to nullptr without delete
3. What is the output of the following code?
int* ptr = new int(10);
std::cout << *ptr << std::endl;
delete ptr;
medium
A. 0
B. 10
C. Garbage value
D. Compilation error

Solution

  1. Step 1: Analyze memory allocation and initialization

    The pointer ptr points to a new integer initialized with 10.
  2. Step 2: Understand output before deletion

    Dereferencing *ptr prints 10 before memory is deleted.
  3. Final Answer:

    10 -> Option B
  4. Quick Check:

    Dereference new int(10) = 10 [OK]
Hint: Dereference pointer before delete to see value [OK]
Common Mistakes:
  • Assuming output is 0 or garbage
  • Thinking delete affects output before cout
  • Confusing syntax causing compile error
4. Identify the error in the following code snippet:
int* arr = new int[5];
delete arr;
medium
A. Pointer arr is not initialized
B. Memory is not allocated properly
C. No error, code is correct
D. Should use delete[] instead of delete

Solution

  1. Step 1: Check allocation type

    Memory allocated with new[] must be deallocated with delete[].
  2. Step 2: Identify mismatch in deallocation

    Using delete instead of delete[] causes undefined behavior.
  3. Final Answer:

    Should use delete[] instead of delete -> Option D
  4. Quick Check:

    Array deallocation = delete[] [OK]
Hint: Match new[] with delete[] always [OK]
Common Mistakes:
  • Using delete for arrays
  • Ignoring pointer initialization
  • Assuming no error in mismatched delete
5. You want to allocate memory for an array of 10 integers and initialize all elements to zero. Which code snippet correctly does this and safely deallocates the memory?
hard
A. int* arr = new int[10](); delete[] arr;
B. int* arr = new int[10]; delete arr;
C. int* arr = (int*)malloc(10 * sizeof(int)); delete[] arr;
D. int* arr = new int(10); delete[] arr;

Solution

  1. Step 1: Allocate and initialize array to zero

    Using new int[10]() allocates an array of 10 integers and initializes all to zero.
  2. Step 2: Properly deallocate array memory

    Memory allocated with new[] must be freed with delete[] to avoid leaks or undefined behavior.
  3. Final Answer:

    int* arr = new int[10](); delete[] arr; -> Option A
  4. Quick Check:

    new[] with () + delete[] = safe zero-init array [OK]
Hint: Use new int[size]() and delete[] for arrays [OK]
Common Mistakes:
  • Using delete instead of delete[] for arrays
  • Mixing malloc/free with new/delete
  • Allocating single int instead of array
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard