0
0
C++programming~10 mins

Memory leak concept in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to allocate memory for an integer pointer.

C++
int* ptr = new [1];
Drag options to blanks, or click blank then click option'
Adouble
Bfloat
Cchar
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different type than the pointer declaration.
Forgetting to use new for dynamic allocation.
2fill in blank
medium

Complete the code to properly deallocate the dynamically allocated memory.

C++
delete [1];
Drag options to blanks, or click blank then click option'
Aptr
Bptr[]
C*ptr
D&ptr
Attempts:
3 left
💡 Hint
Common Mistakes
Using delete[] for single object allocation.
Deleting the dereferenced pointer instead of the pointer.
3fill in blank
hard

Fix the error in the code that causes a memory leak by missing deallocation.

C++
void leak() {
    int* data = new int[10];
    // Missing [1]
}
Drag options to blanks, or click blank then click option'
Afree(data)
Bdelete data
Cdelete[] data
Ddelete *data
Attempts:
3 left
💡 Hint
Common Mistakes
Using delete instead of delete[] for arrays.
Not deleting allocated memory at all.
4fill in blank
hard

Fill both blanks to create a loop that allocates and then deallocates memory correctly.

C++
for (int i = 0; i < 5; i++) {
    int* ptr = new [1];
    // use ptr
    [2] ptr;
}
Drag options to blanks, or click blank then click option'
Aint
Bdelete
Cdelete[]
Dfloat
Attempts:
3 left
💡 Hint
Common Mistakes
Using delete[] for single object allocation.
Forgetting to delete the allocated memory inside the loop.
5fill in blank
hard

Fill all three blanks to create a dictionary-like structure using std::map that stores dynamically allocated integers and properly deletes them.

C++
#include <map>
#include <string>

void cleanup(std::map<std::string, int*>& data) {
    for (auto& [1] : data) {
        [2] [3];
    }
    data.clear();
}
Drag options to blanks, or click blank then click option'
Apair
Bdelete
Cpair.second
Dauto
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect loop variable type.
Forgetting to delete the pointers before clearing the map.