'About C++ memory leak

I want to ask some of the problems about C++ memory leak. And what is my mistake of my programme and how to rewrite the programme to prevent memory leak. Thank you

int **ptr = new int*[5];
for (int i = 0; i < 5; i++)
  ptr[i] = new int (i+1);
delete ptr;
c++


Solution 1:[1]

Don't use raw pointers when avoidable. Use std::vector instead.

std::vector<int> ptr(5);
for (int i = 0; i < 5; i++) {
  ptr[i] = i+1;
}

If you are forced to use raw pointers for some reason, delete whatever you allocated. Also note that you have to use delete[] to delete what is allocated via new[].

int **ptr = new int*[5];
for (int i = 0; i < 5; i++)
  ptr[i] = new int (i+1);

for (int i = 0; i < 5; i++)
  delete ptr[i];
delete[] ptr;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MikeCAT