Bird
Raised Fist0
C++programming~5 mins

Memory allocation and deallocation in C++

Choose your learning style10 modes available
Introduction

Memory allocation lets your program get space to store data while running. Deallocation frees that space when you no longer need it, so your computer can use it for other things.

When you need to create variables or objects during the program that you don't know the size of before running.
When you want to manage memory yourself to use it efficiently.
When you create data structures like linked lists or trees that grow or shrink while the program runs.
When you want to avoid wasting memory by only using what you need.
When you want to prevent your program from crashing by cleaning up unused memory.
Syntax
C++
int* ptr = new int;       // allocate memory for one int
int* arr = new int[5];    // allocate memory for an array of 5 ints

// use the memory
*ptr = 10;
arr[0] = 1;

// free the memory
delete ptr;               // free single int
delete[] arr;             // free array

new gives you memory from the heap to use.

delete returns that memory back to the system.

Examples
This example shows how to allocate and free memory for a single integer.
C++
int* p = new int;  // allocate one int
*p = 42;            // store value

// later
delete p;            // free memory
This example shows how to allocate and free memory for an array of integers.
C++
int* arr = new int[3];  // allocate array of 3 ints
arr[0] = 5;
arr[1] = 10;
arr[2] = 15;

// later
delete[] arr;            // free array memory
Sample Program

This program shows how to allocate memory for a single integer and an array, use them, then free the memory to avoid waste.

C++
#include <iostream>

int main() {
    int* number = new int;       // allocate memory for one int
    *number = 100;              // store value

    int size = 3;
    int* array = new int[size]; // allocate array
    for (int i = 0; i < size; i++) {
        array[i] = i * 10;      // fill array
    }

    std::cout << "Number: " << *number << "\n";
    std::cout << "Array values: ";
    for (int i = 0; i < size; i++) {
        std::cout << array[i] << " ";
    }
    std::cout << "\n";

    delete number;              // free single int
    delete[] array;             // free array

    return 0;
}
OutputSuccess
Important Notes

Always use delete for memory allocated with new to avoid memory leaks.

Use delete[] to free arrays allocated with new[].

Failing to free memory can cause your program to use too much memory and slow down or crash.

Summary

Memory allocation reserves space for data during program run.

Memory deallocation frees that space when done.

Use new and delete carefully to manage memory safely.

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