Dynamically creating array of object on the heap:
MyClass** objects;
arrSize = 100;
objects = new MyClass*[arrSize]; //Note the '*' before arrSize
for (size_t i = 0; i < arrSize; i++) {
objects[i] = new MyClass();
}
Freeing up heap memory allocated to object array:
for (size_t i = 0; i < arrSize; i++) {
delete objects[i];
}
delete[] objects;
Tip: You can use Visual Studio's Memory Usage diagnostic tool to check heap memory changes which gives clues about memory leaks. To get the function names where memory is allocated but then never released, use valgrind on WSL (Linux) as follows:
valgrind --tool=memcheck --leak-check=yes ./<app name>
No comments:
Post a Comment